# Question
Title: 3D Camera Rotation (Unwanted Roll) - Space/Flight Cam
I am working on a camera class that will have full range of motion (pitch, yaw, and roll). When only altering pitch and yaw, I am getting a large amount of roll.

I understand that the issue is related to: I'm rotating an object on two axes, so why does it keep twisting around the third axis?

However, I have not been able to come up with a solution. I would like the camera to have all motion (i.e. like a spaceship). Here is the relevant code:

```
void Camera3D::update(const glm::vec2 & current_mouse_coords){

    if (m_mouse_first_movement) {
        if (current_mouse_coords.x != 0 || current_mouse_coords.y != 0) {
            m_mouse_first_movement = false;
        }
    } else {
        const glm::vec2 mouse_delta = (current_mouse_coords - m_old_mouse_coords) * mouse_sensitivity;
        pitch(-mouse_delta.y);
        yaw(-mouse_delta.x);
    }
    m_old_mouse_coords = current_mouse_coords;
}

void Camera3D::pitch(const float angle){

    // Pitch Rotation
    const glm::quat pitch_quaternion = glm::angleAxis(-angle, m_camera_right);

    // Update Vectors
    m_camera_up = glm::normalize(glm::rotate(pitch_quaternion, m_camera_up));
    m_camera_forward = glm::normalize(glm::rotate(pitch_quaternion, m_camera_forward));
}

void Camera3D::yaw(const float angle){

    // Yaw Rotation
    const glm::quat yaw_quaternion = glm::angleAxis(angle, m_camera_up);

    // Update Vectors
    m_camera_right = glm::normalize(glm::rotate(yaw_quaternion, m_camera_right));
    m_camera_forward = glm::normalize(glm::rotate(yaw_quaternion, m_camera_forward));
}

glm::mat4 Camera3D::get_view_matrix(){
    m_view_matrix = glm::lookAt(
        m_camera_position,
        m_camera_position + m_camera_forward,
        m_camera_up
    );
    return m_view_matrix;
}

```

I would like the movement of the camera to be based on local coordinates so the controls (up/down/left/right/vertical up/vertical down) move the camera along its own local axis.

Additional clarification based on the comment below: If I look up 60 degrees and then left, I would like the horizon to stay level (essentially adding roll in the opposite direction to keep the horizon level)

Any help is appreciated. Thank you!

# Answer
> 0 votes
Thanks for all answers. Here was my solution:

The camera is set to have 2 modes (for now). The two modes are:

* Flight (Fixed Yaw Axis)
    +
    + Regardless of where the camera is looking, yaw is rotated along the global y axis. This was based on the linked post that 'DMGregory' wrote. As you can see from the gif, this has the effect of 'stabilizing' the horizon. Pitch is clamped at +/- 85 degrees. Flight movement controls are based on local camera coordinates. For example, when I use vertical up movement, this uses the cameras local up axis, not the global y axis. In order to get this axis, I simply take the cross product of the camera\_forward vector with the camera\_right vector. I can also see how a user may want vertical up/down to be tied to the world up/down, and will probably make that an option (i.e. setting the vertical movement axis as the world\_up).
* Flight (Roll Enabled)
    +
    + For flight mode without a fixed yaw axis, everything is based on local camera coordinates. Yaw is being replaced by roll in this mode and is not used at all. Roll is done along the cameras forward vector. This gives a fairly natural feel for how you would control a spaceship. This also has the added benefit of not running into any gimbal lock, so there is full rotation along any axis. The movement vertical up/down controls are based on the local camera\_up vector. As a side note, yaw could also be included in this mode (along the local cameras up vector). However, for my camera system I added a toggle between modes. When the user is in fixed yaw mode, left and right on the mouse result in yaw changes. When the user enters flight without fixed yaw, roll is used based on left and right mouse movement. Yaw could be added in and tied to a key if desired.

# Answer
> 3 votes
It seems like you accumulate transformations. What you need to do instead is to keep rotation as euler angles pitch and yaw and then calculate final rotation from them.

---
Tags: opengl, c++, camera, rotation, quaternion
---


title: Convert a string to a gameobject name

text:
# Question
Title: Convert a string to a gameobject name
I want to use a string to reference a gameobject that I already have in my code, but the console says that you can't convert a string to unityengine.object. I have a string that says `aaaa` and a gameobject that has the name `aaaa`.

using System.Collections.Generic;
using UnityEngine;

public class WorldRenderer : MonoBehaviour
{

    public Transform Tile;

    string seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacaaabaaaaaaaa";

    public int worldHeight;
    public int worldWidth;

    private int seedSub = 0;

    public GameObject aaaa;
    public GameObject aaab;
    public GameObject aaac;

    void Start()
    {

        transform.position = new Vector3(worldWidth / 2 * -0.64f + 0.32f, worldHeight / 2 * 0.64f + 0.32f);

        for (int height = 0; height < worldHeight; height++)
        {

            transform.position = new Vector3(worldWidth / 2 * -0.64f - 0.32f, transform.position.y);
            transform.position = transform.position - new Vector3(0, 0.64f);

            for (int width = 0; width < worldWidth; width++)
            {

                seedSub = seedSub + 1;

                transform.position = transform.position + new Vector3(0.64f, 0);
                //Here's the problem VVV
                GameObject tilepos = Instantiate(seed.Substring(seedSub * 4 - 3, 4)) as GameObject;
                //Here's the problem ^^^
                tilepos.transform.position = new Vector2(transform.position.x, transform.position.y);

            }

        }

    }

}```
</code></pre>

# Answer
I looks like you want to match not the game object name, but the name of your variable. You can do that with a dictionary, something like this:

```
void Start() {
    var patternMatch = Dictionary<string, GameObject>(3);

    // Add each of your game objects into a collection, with their string as a key.
    patternMatch.Add("aaaa", aaaa);
    patternMatch.Add("aaab", aaab);
    patternMatch.Add("aaac", aaac);

    //...then later, inside your for loop...

        // Form the key you want to search for.
        string key = seed.Substring(seedSub * 4 - 3, 4);

        // Look for a matching entry in your dictionary, and error if missing.
        if(!patternMatch.TryGetValue(key, out GameObject prefab)) {
            Debug.LogErrorFormat("Could not find matching prefab for pattern \"{0}\"", key);
            continue;
        }

        // Now we can use the object we looked up.
        GameObject tile = Instantiate(prefab,
                                      new Vector3(transform.position.x, transform.position.y),
                                      Quaternion.Identity);

   // ...end of your loop
}

```
> 1 votes

---
Tags: unity, c#, visual-studio
---


title: Libgdx opacity partial error

text:
# Question
Title: Libgdx opacity partial error
My model must support transfer textures but I can't do this using mesh + modelBuilder.part

Opacity is tested correctly on only half of the model.

```
BlendingAttribute blendingAttribute = new BlendingAttribute();
        blendingAttribute.opacity = 1.0f;

        modelBuilder = new ModelBuilder();
        modelBuilder.begin();
        modelBuilder.part("minecraft:loading_model", mesh, 4, new Material(TextureAttribute.createDiffuse(atlas), blendingAttribute));
        modelInstance = new ModelInstance(modelBuilder.end());

```

# Answer
I found the solution in a badlogic forum.

This:

```
modelBuilder.part("minecraft:loading_model", mesh, 4, new Material(TextureAttribute.createDiffuse(atlas), blendingAttribute, FloatAttribute.createAlphaTest(0.95f)));

```

Or this:

```
modelInstance.materials.get(0).set(FloatAttribute.createAlphaTest(0.95f));

```
> 1 votes

---
Tags: java, libgdx, android
---


# Question
Title: Frame-rate drops when drawing 2D map tiles
**Update:** I figured out it has nothing to do with the camera but instead framerate drops when drawing my map tiles onto the screen.

Here’s a link to a video showcasing the bug in action (For further reference): https://streamable.com/m4zuf3

Any and all guidance is appreciated, thanks.

Here's the draw functions:

```
    protected override void Draw(GameTime gameTime)
    {
        m_mainLevel.Draw(spriteBatch);
    }

```

```
        public void Draw(SpriteBatch sb)
        {
            //Draw Background
            for (var i = 0; i < BackgroundTiles.Length; i++)
            {
                int id = BackgroundTiles[i].m_id;

                int column = id % TilesetTilesWide;
                int row = (int)Math.Floor((double)id / (double)TilesetTilesWide);

                int width = Map.TileWidth * 2;
                int height = Map.TileWidth * 2;

                float x = (i % Map.Width) * width;
                float y = (float)Math.Floor(i / (double)Map.Width) * height;

                Rectangle tilesetRec = new Rectangle(TileWidth * column, TileHeight * row, TileWidth, TileHeight);
                Rectangle dest = new Rectangle((int)x, (int)y, width, height);
                sb.Draw(Tileset, dest, tilesetRec, Color.White);
            }
        }

```

Is the problem that I'm drawing too many tiles per frame? the map size is 250 x 250 tiles, with each tile being 16x16px.

# Answer
> 0 votes
I solved it.

```
if(bounds.Intersects(dest)) sb.Draw(Tileset, dest, tilesetRec, Color.White);

```

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


# Question
Title: How to render a large, seamless platforming world without scene transitions?
In the game Limbo for example, the whole 2-3 hours of gameplay takes place in one continuous world. The player navigates from one area to another seamlessly, with no obvious loading or transitions.

It looks like the whole game world (ie. all the ground sprites and every puzzle) is always active on and off camera. Is that feasible?

How can I make a large world like this without overwhelming the player's device with all the content that needs to be loaded?

# Answer
Well, basic setup of desired configuration can be achieved quite easily in Unity.

`SceneManager` class has nice methods: LoadSceneAsync and UnloadSceneAsync. They are loading/unloading scenes in the background and provide convenient callbacks when scene loading is complete; you can initialize more than one scene like this:

```
 SceneManager.LoadSceneAsync("DesiredSceneName", LoadSceneMode.Additive);

```

This way already loaded scene stays untouched and the second scene is loaded in additive mode. If there are more than one scene initialized, all GameObjects from all scenes are displayed. You have options to Merge Scenes or to Move GameObject from one Scene to another. DontDestroyOnLoad is also nice for objects continuously traveling between scenes.

So the game world is split into different scenes, which are loaded in background and seamlessly linked together. How to arrange scenes loading/unloading is up to you:

* You can set up triggers near scene borders, which start loading adjacent scenes when entered.
* You can automatically load neighboring scenes when player crosses scene borders and unload all others so at any time you would have 3 scenes loaded: current, previous and next.

Another important note is that additive scenes might overlap each other, so you'll need to offset objects on each scene or write a script which places scene gameobjects in required location.

(For example, there is popular trick: move all UI to separate scene in additive mode to keep other scenes as clean as possible; UI must not be destroyed when scene is changed after all)
> 1 votes

# Answer
Modern hardware is powerful and platformers are often pretty lightweight, so keeping the whole game world for a 2-3 hour game in one single scene might not be as infeasible as it might seem. So I would recommend you to just start building your game in one scene until you actually notice problems with low framerate or excessive RAM use... or if you have multiple level designers and need to enable them to work on different parts of the game world in parallel.

When you actually do have the problem, then there are a couple things you can do:

* Deactivate objects which are more than a couple screens away from the camera and activate them when the player comes into range (usually doesn't do much for RAM but can conserve some CPU and GPU instructions).
* Convert your game into sections which you load and unload dynamically when the player comes into range. Those sections can be represented by prefabs or by scenes you load with `LoadSceneMode.Additive` (as in the answer by Xamtouo)
* Use scene transitions, but hide them well. Place your scene transitions in relatively "boring" areas with no moving objects. Duplicate these sections exactly in both scenes. When the player moves from one scene to another, make sure their position and state get accurately transferred to the next scene. If you do it well, you can hide any indication that there was a scene switch.
> 0 votes

---
Tags: unity, platformer, levels, scenemanager, streaming
---


# Question
Title: How to rotate sides of rubik's cube by mouse drag?
I am trying to make a Rubik's cube simulator. I built the Cube by arranging 27 pieces in appropriate place. I wanna simulate the cube like This.
This is what my cube looks like.

I successfully wrote a simple script to rotate the whole cube while dragging the mouse on background. I was also able to rotate sides with key inputs like U, F etc. For this I created 6 empty game objects (UpLayer, FrontLayer etc.) and positioned them in centre of corresponding sides. I store every piece in an array. Now, when the user presses a key, suppose U, I

1. Make all 9 pieces of upper layer child of empty game object UperLayer at runtime.
2. Rotate the UperLayer object around its local y axis 90 degrees.
3. Make required changes in the array.
4. Un-parent all the pieces.

It works perfectly for every layer. But now, I wanna rotate the layer when user drags it with mouse (Check the above link). I can't think of any approach to do so. I need help.

# Answer
Here's an outline of the steps.

1. Cast a ray through the mouse position (using `Camera.ScreenPointToRay()`) to hit a boxcollider on your sub-cube. This will give you the position and normal of the point.
2. You have two potential axes of rotation: the two axes perpendicular to the normal. But we don't yet know which one the player wants to rotate around.

Add a small multiple of each of these axes to your hit point in the world, and project those back to the screen (using `Camera.WorldToScreenPoint()`), then subtract the position of the cursor and normalize. Now you have two unit vectors in screenspace representing the valid drag directions. Store them to use on subsequent frames.
3. While the player keeps the mouse button held, subtract the current mouse position from the screen position where they first clicked to get the displacement of the drag so far.

Take the dot product of this displacement with each of the screenspace unit vectors you computed previously to get the pixel travel in that direction. Take the absolute value of each. Whichever one first exceeds a sensitivity threshold you choose (accounting for a little wobble when starting the drag), that one gets chosen as the rotation direction, and the *opposite* axis becomes the axis of rotation.

Now we're ready to start rotating.
4. Gather all 8-9 sub-cubes in the row/column perpendicular to your chosen rotation axis, and store them in a collection, along with their initial offset from the center of the cube, and their initial orientation.
5. Form a rotation quaternion spinning about your rotation axis, by a number of degrees proportional to your drag's pixel distance along your rotation direction vector.

If desired, keep track of a second rotation quaternion that starts at the identity, and "chases" the one above at a controlled speed or blend rate, so you can smooth sudden changes, and use this one to transform your sub-cubes.
6. Transform all your sub-cubes' initial offsets & rotations by this quaternion, and place them there.
7. When the player releases, find the closest multiple of 90 degrees to their last rotation angle, and blend your transformation quaternion to that value. Don't let the player start a new drag until this is complete.
8. Once you've finished blending to the rounded rotation, you can clear all these drag state variables and re-enable a new drag.

This is also a good time to go apply a small fix-up to any moved cubes, ensuring they've landed exactly at integer coordinates, and that their orientation is one of the 24 cardinal orientations, so you prevent any rounding error from accumulating over repeated drags.

If you have trouble with any particular one of the steps above, folks here should be able to give you more guidance on how to achieve it.

---

Here's a working example of this in code, now that I've had a chance to test it.

This assumes your sub-cubes are axis-aligned, positioned at -1, 0, 1 on each axis, and have box colliders we can use to detect raycast hits or gather them with an overlap query. I also assume you use a single fixed camera angle.

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

public class Rubik : MonoBehaviour
{
    public float minimumDragPixels = 3.0f;
    public float dragSensitivity = 3.0f;
    public float snapSpeed = 90.0f;

    Camera _camera;

    Collider[] _subCubes = new Collider[9];
    Vector3[] _originalPositions = new Vector3[9];
    Quaternion[] _originalOrientations = new Quaternion[9];

    IEnumerator Start() {
        _camera = Camera.main;
        Vector3 camForward = _camera.transform.forward;
        float axisSign = Mathf.Sign(camForward.x * camForward.y * camForward.z);

        while(true) {
            yield return null;

            // Keep waiting until the player presses the mouse button.
            if (!Input.GetMouseButton(0))
                continue;

            // Step 1: Fire a ray through the mouse position.
            Vector2 clickPosition = Input.mousePosition;
            var ray = _camera.ScreenPointToRay(clickPosition);

            // If we didn't hit anything, try again next frame.
            if (!Physics.Raycast(ray, out RaycastHit hit))
                continue;

            // Step 2: find the two potential axes of rotation.
            int normalAxis = Mathf.Abs(Mathf.RoundToInt(Vector3.Dot(
                    hit.normal,
                    new Vector3(0, 1, 2)
                )));

            Vector3 rotationAxis = Vector3.zero;
            Vector3 alternativeAxis = Vector3.zero;

            rotationAxis[(normalAxis + 1) % 3] = 1;
            alternativeAxis[(normalAxis + 2) % 3] = 1;

            // This sign fiddling just ensures our drag direction matches the visible rotation.
            float signFlip = axisSign * Mathf.Sign(Vector3.Dot(rotationAxis, camForward) * Mathf.Sign(Vector3.Dot(alternativeAxis, camForward)));
            Vector2 rotationDirection = signFlip* ScreenDirection(clickPosition, hit.point, alternativeAxis);
            Vector2 alternativeDirection = -signFlip * ScreenDirection(clickPosition, hit.point, rotationAxis);

            // Step 3: wait until we've dragged far enough to pick an axis.
            float signedDistance;
            do {
                yield return null;

                Vector2 mousePosition = Input.mousePosition;
                signedDistance = DistanceAlong(clickPosition, mousePosition, rotationDirection);
                if (Mathf.Abs(signedDistance) > minimumDragPixels)
                    break;

                signedDistance = DistanceAlong(clickPosition, mousePosition, alternativeDirection);
                if (Mathf.Abs(signedDistance) > minimumDragPixels) {
                    rotationAxis = alternativeAxis;
                    rotationDirection = alternativeDirection;
                    break;
                }

            } while (Input.GetMouseButton(0));

            // Step 4: Gather the 8-9 sub-cubes we need to rotate.
            Vector3 extents = Vector3.one - 0.9f * rotationAxis;
            extents = extents * 2.0f;
            int subCubeCount = Physics.OverlapBoxNonAlloc(hit.collider.transform.position, extents, _subCubes);

            for(int i = 0; i < subCubeCount; i++) {
                var subCube = _subCubes[i].transform;
                _originalPositions[i] = subCube.position;
                _originalOrientations[i] = subCube.rotation;
            }

            // Step 5-6: Rotate the group by the input angle each frame.
            float angle = 0.0f;
            while (Input.GetMouseButton(0)) {
                angle = signedDistance * dragSensitivity;
                RotateGroup(angle, rotationAxis, subCubeCount);

                yield return null;
                Vector2 mousePosition = Input.mousePosition;
                signedDistance = DistanceAlong(clickPosition, mousePosition, rotationDirection);
            }

            // Step 7: After release, snap the angle to a multiple of 90.
            float snappedAngle = Mathf.Round(angle / 90.0f) * 90.0f;

            while(angle != snappedAngle) {
                angle = Mathf.MoveTowards(angle, snappedAngle, snapSpeed * Time.deltaTime);

                RotateGroup(angle, rotationAxis, subCubeCount);
                yield return null;
            }

            // Step 8: Loop back and wait for the next drag.
            // TODO: Consider correcting for any accumulated rounding errors.
        }
    }

    Vector2 ScreenDirection(Vector2 screenPoint, Vector3 worldPoint, Vector3 worldDirection) {
        Vector2 shifted = _camera.WorldToScreenPoint(worldPoint + worldDirection);

        return (shifted - screenPoint).normalized;
    }

    float DistanceAlong(Vector2 clickPosition, Vector2 currentPosition, Vector2 direction) {
        return Vector2.Dot(currentPosition - clickPosition, direction);
    }

    void RotateGroup(float angle, Vector3 axis, int count) {

        Quaternion rotation = Quaternion.AngleAxis(angle, axis);

        for (int i = 0; i < count; i++) {
            var subCube = _subCubes[i].transform;
            subCube.position = rotation * _originalPositions[i];
            subCube.rotation = rotation * _originalOrientations[i];
        }
    }
}

```
> 0 votes

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


# Question
Title: Unity - Proper rotation of object from 3 points in space
I have a rectangular object (for now), with children placed partially in it in its forward, up, and right sides (to make rotations easier to track).

I am trying to get the object to rotate according to 3 points in space. One is the origin (0,0,0), one is in the forward direction (0,0,1), and one is in the right direction (1,0,0).

The origin and forward direction are how I define the origin and direction, so these coordinates are local. I assume for now that the right direction is correct for now.

My simple solution was to set `transform.forward = (forward-origin);` and `transform.right = (right-origin);` (where the points are given in global coordinates).

My problem with this is that the rectangular object won't roll around its forward direction. I'm not great with geometry, but I can't get past the thought that setting `right` ought to solve that problem.

I was, however, not surprised to see that trying to set `transform.up` as the cross-product of those two made things worse and the object was no longer facing in the forward direction.

So,

1. Why doesn't the combination of `forward` and `right` account for this rolling?
2. What if `right` weren't *exactly* right? I'm assuming simply normalizing it against `forward` would do it (and with unity, I could also get `up` out of it with one function call), but I'm not certain.

# Answer
When you set one direction vector at a time, Unity doesn't know you're about to set another one. The semantics of the language make each assignment a separate operation, and it needs to give you a complete new orientation after each one, not a partial transformation-in-progress.

So if you set `transform.forward = foo`, Unity has 2 of 3 degrees of freedom specified, and it has to *guess* what you wanted for the third. Sometimes it will guess wrong.

Then if you set `transform.right = bar`, Unity again has 2 of 3 degrees of freedom specified, and it has to *guess again*. Sometimes it will guess wrong.

It doesn't know the two operations are connected - for all it can tell, you changed your mind after the first assignment, and now want a completely different, unrelated orientation from the second assignment. (If it didn't make this assumption, transform operations would have a "memory" you'd have to manually clear between uses, which would be clunky)

If you want *both* forward *and* right to point in particular directions, you need to express that as a single transformation, not as two separate steps. Here's one way to do it:

```
Vector3 forwardDirection = forwardPosition - origin;
Vector3 rightDirection = rightPosition - origin;
Vector3 upDirection = Vector3.Cross(forwardDirection, rightDirection);

Quaternion orientation = Quaternion.LookRotation(forwardDirection, upDirection);

transform.rotation = orientation;

```

This will give you an orientation whose forward vector points exactly along your chosen forward direction, and whose right vector points as close as it can along your chosen right direction while still obeying the first constraint (since we have only 1 degree of freedom left).
> 2 votes

---
Tags: unity
---


# Question
Title: How to make an illusion where the contents of a 3D shape change based on which face you look through?
I remember coming across a Unity 3D tutorial where there was a technique where the contents of a 3D shape change based on which face you are looking at, similar to this screenshot from Antichamber:

What is this techique called? And how do I implement it into a Unity 3D project?

Thanks in advance.

# Answer
This is related to portal rendering. Typically this kind of effect is implemented with the stencil buffer.

You render each "viewport" on the shape's surface with a material that sets the stencil buffer to a specific value, but doesn't write to the z-buffer. Each face uses its own distinct value.

Then you render the contents of each view, using a material that checks whether the stencil buffer contains that specific key value. If it does, the object draws its pixels there. If it doesn't, those pixels are skipped.
> 2 votes

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


# Question
Title: How do I safely change properties on my skybox?
Usually in Unity, when your scripts make changes to something at runtime, those changes are not persisted back to design-time. This is generally considered a good thing. But for whatever bizarre technical reason, this does not apply to shader properties on materials. If you change something while the game is running, it stays changed!

Generally the way to get around this is with a `MaterialPropertyBlock`, which also helps avoid generating a lot of garbage. But `MaterialPropertyBlock`s work with `Renderer`s, which leaves out one rather important material: the skybox.

Right now, I have code that says `RenderSettings.skybox.SetFloat("_PropName", value);`, and it's incredibly aggravating because it always needs to be reset afterwards. `RenderSettings` doesn't have a `SkyboxRenderer` property that I can use in conjunction with a `MaterialPropertyBlock`, so how can I change shader settings on my skybox and make them not persist after I exit play mode?

# Answer
Presumably you considered doing something like...

```
Material originalSkybox = RenderSettings.skybox;
Material runtimeSkybox = Instantiate(originalSkybox);
RenderSettings.skybox = runtimeSkybox;

runtimeSkybox.SetFloat(...

```

...and destroying `runtimeSkybox` when your game ends?
> 1 votes

---
Tags: unity, materials, skybox
---


# Question
Title: Clamp quaternion relative to plane normal
How would one be able to clamp a quaternion based on the angle relative to a plane surface (defined by a normal)?

My diagram below provides more of a visual explanation of exactly what I am talking about.

The quaternions are clamped based on the angle between the planes surface, and the quaternion's forward vector (i.e. `q * (0, 0, 1)`). The quaternions are global quaternions. The plane normal (vector) **N** defines the upwards direction of the plane surface. Angles that go opposite of the normal vector is negative, whereas in the direction is positive. With that in mind, the quaternion's angle cannot be greater than **MAX** degrees and less than **MIN** degrees. These bounds are visualized by the cones (**MIN** is *-90˚* in the diagram, so the cone is infinitely thin).

**Thoughts:**

My thought is that this algorithm would have to work in regards to the quaternions *delta* (unless the quaternion is in the **MIN**/**MAX** zones, which I will talk about later). If the change (*delta*) of the quaternion results in the quaternion entering, or passing, the bounds, the change is capped (clamped) so the final quaternion never has a resulting angle that dissatisfy the bounds.

Clamping the delta could be achieved by determining the beginning and end angles, and obtaining a ratio to be used as the *t* value (the interpolator) of a *Slerp* function, so the final quaternion's angle is that of the bound. The issue I see with this is how the roll would be manipulated due to the Slerp. Would the intended, final roll of the quaternion be lost due to this Slerping?

This idea of change seems more important in the example of if the quaternion was to go from -89˚ to -91˚. The final quaternion should be snapped back to -90˚ (if the bound was -90), instead of considering the new quaternion as -89˚ but from the other side. Without this proper interpretation of the quaternion's angle, the quaternion could rotate around constantly and consistently due to the angle never being considered less than -90˚ and greater than 90˚.

**Edge Case:**

If the quaternion was to start inside the **MIN**/**MAX** zones (the cones), the quaternion would not have a change to define as the direction that the quaternion needs to move to get back to legal territory/angles (see angle *a3* in diagram). My thoughts is that a fallback plane normal that is orthogonal to plane normal **N** would have to be used, so the quaternion has a plane to rotate around.

**Use Case:**

Orbiting camera with user or author definable pitch angle clamping, and a varying change in "up". Example of varying change of "up": *Mario Kart 8 Deluxe*.

# Answer
> 1 votes
One idea is that you transform to a coordinate system where up is actually `Vector3.up` then do whatever clamping you need via standard Euler angles, and then transform it back.

So I think something like this (this is the version in Unity C#, but take it as pseudocode) would work:

```
    public Quaternion GeneralEulerClamp(Vector3 targetNormal, Quaternion inputrotation) {
        Vector3 xyz = Vector3.Cross(Vector3.up, targetNormal).normalized * Mathf.Sqrt((1 - Vector3.Dot(Vector3.up, targetNormal)) / 2);
        Quaternion coordchange = new Quaternion(xyz.x, xyz.y, xyz.z, Mathf.Sqrt(1 - xyz.sqrMagnitude));
        Vector3 EA = (coordchange * inputrotation).eulerAngles;//Note that quaternion multiplcation is not commutative!
        EA = new Vector3(Mathf.Clamp(EA.x,-90,70), EA.y, EA.z);//set EA.z to zero if you don't want roll
        Quaternion result = new Quaternion();
        result.eulerAngles = EA;
        result = Quaternion.Inverse(coordchange) * result;//It's possible that the first application of coordchange is the inverse and this one isn't
        return result;
    }

```

`targetNormal` here needs to be normalized.

So here, coordchange is a rotation rotates `targetNormal` to `Vector3.up`. We apply that rotation to the input (by multiplying quaternions), then find the Euler angles. Then we do some clamp operations on the Euler angles and turn in back into a quaternion. Then we do the inverse of the coordchange operation to move `Vector3.up` back to `targetNormal`.

Not 100% sure if I worked out my trig correctly since I don't have a way to test this (most likely error is that I got the sign of xyz wrong), but the general concept can work like this.

---
Tags: mathematics, rotation, quaternion
---


# Question
Title: What are some of the tricks engine can use to render object that have extremely high polygons efficiently?
What are some of the tricks engine can use to render object that have extremely high polygons efficiently? I know one thing we do is render only the parts that the camera points at, but I am wondering if there are many more techniques used other than that one.

# Answer
There are three basic approaches to this problem.

**Render Less**

This includes techniques that allow you to skip rendering polygons that are not visible, while maintaining a high polygon count for those that are visible. It might include backface culling, frustum culling, visibility culling; LOD techniques might also fit here.

**Render More Efficiently**

Batching is the classic technique here, but it might also include scene traversal optimizations, shader optimizations, and other techniques that let you get more work out of available compute resources.

**Fake It!**

This includes techniques that let you take a low polygon representation and make it look like high polygon; normal mapping is one classic such technique, but it may also include tessellation or dynamic geometry creation.

On the whole you won't use one of these techniques in isolation, although batching is the one that is most likely to give you best results across the widest variety of use cases.
> 2 votes

---
Tags: physics, rendering
---


# Question
Title: How to correctly solve a procedurally generated puzzle?
I'm creating a puzzle game where the player must remove all colored blocks from a grid. When the player selects a block, all adjacent blocks of the same color are removed. Any blocks that have empty cells below them will then fall into those cells. Here's a simple illustration of the mechanic:

https://i.stack.imgur.com/fE7aV.jpg

The game will procedurally generate puzzles with varying degrees of difficulty. When the player completes a puzzle the game will then score the player based on how quickly and, more importantly, how efficiently they solved the puzzle.

The problem I am having is implementing a method of determining the most efficient way of solving a puzzle (i.e. identifying the fewest number of moves possible). Here's an example of a puzzle that was generated:

https://i.stack.imgur.com/Qhgvc.jpg

As a human, I could identify that the fewest number of moves that could be made to solve this puzzle was 11. Here is a gif of the solve:

https://imgflip.com/gif/463qck

However, when I whipped up an application that just clicked blocks at random in order to solve this puzzle, the lowest number of moves that it was able to solve this in was 14. And this was over billions of iterations which took many minutes. Obviously that is not acceptable. I need to find the correct solution and it should be done within seconds.

I also tried to reverse-engineer the generation process but that doesn't work. For example, it could place a blue block in column 1, a bunch of other blocks, a red block in column 1, a bunch of other blocks, then another blue block in column 1. Column 1 could be resolved in 2 moves (by clicking the red block and then one of the blue blocks), which reverse-engineering the generation would not detect.

So, my question:

What kind of techniques or tricks can I implement that will allow the application to resolve this type of generated puzzle quickly and correctly? I'm sadly out of ideas.

# Answer
My advice would be to generate the puzzles by running your solving algorithm in reverse: Add connected shapes that displace the squares they occupy and the squares above them up.

The number of shapes you add may not be the minimal amount of moves to solve the puzzle but it will give you a good estimate of a good solve. Anything below that number will probably be a great solve, especially if you use some heuristic to minimize shapes of the same color in overlapping or neighboring columns during generation.
> 4 votes

---
Tags: algorithm, logic
---


# Question
Title: Why does Unity let you install iOS Build Support on Windows?
When installing Unity on a Windows machine, you are allowed to select "iOS Build Support" as one of the components to install. However, it is not possible to make an iOS build from Windows. Why is this package available on Windows? What does it offer?

# Answer
As far as i know when you build for IOS on windows it will generate an Xcode project that you then need to build on mac.

As you can't make IOS bundles on windows the only thing you can do is to make the process better by not having the requirement of installing Unity on both windows and OSX. You could set up automated tools which take the output from unity and automatically build the game on a mac so that you don't have to go though as many hoops. See Jenkins.

Hope this helps :)
> 14 votes

# Answer
Developing on Windows and building on Mac is the major reason for its existance on Windows! Lots of programmers does not like to code on Mac. And `iOS build support on Windows` make modifying iOS buildsettings on Windows be possible!
> 0 votes

---
Tags: unity, ios, build-process
---


# Question
Title: A star pathfinding path too narrow for enemy
The tiles for my top down 2D shooter are 32x32 and the player and enemies are too. But obstacles like walls and other things can of course be smaller than this - the smallest being 8x8. This causes a problem where a single 8x8 barrier intruding in a 32x32 tile will cause that whole tile to be impassable if my AI Grid is based on 32x32 tiles, like as follows:

This results in a grid with more impassable area than it should have. (On the left the red being the AI grid's impassable area, and on the right, the green being the box2d barriers for the same map section).

The other option is to make the grid 8x8 based and then the grid will perfectly calculate the actual impassable areas but it will create paths too narrow for the 32x32 enemy to pass through. With design I can make the first way (pathfinding grid of 32x32 tiles) work but it's not ideal since you're limited to placing everything in perfect tiles so as to not create impassable areas that are in fact passable.

# Answer
You can make your grid 8x8 and expand all impassible tiles into a 4x4 patch of impassible tiles. Or in other words a tile is impassible if any of the tiles in a 4x4 region around it is impassible.

Then you can path find based on a 1x1 entity on that modified grid and when you make an entity follow that path you expand it's location opposite as you expanded your walls (swap left and right in your expansion).

In effect I created the minkowski sum between the obstacles and your enemy's hitbox. That way you can shrink the bounding box of the pathing agent to a point. This technique is also called dilation.

To copy give an example, take this map with 1 as impassible tiles and 0 as walkable.

```
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 1 0 0 0 0
0 1 1 1 1 1 1 0 0 0 0
0 1 0 0 0 1 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0

```

with a 4x4 dilation (2 up and right, 1 down and left) this turns into the following map with 2 as the expanded tiles:

```
2 2 2 2 0 0 0 0 0 0 0
2 2 2 2 0 0 0 0 0 0 0
2 1 2 2 0 0 0 0 0 0 0
2 1 2 2 0 2 2 2 2 0 0
2 1 2 2 2 2 2 2 2 0 0
2 1 2 2 2 2 1 2 2 0 0
2 1 1 1 1 1 1 2 2 0 0
2 1 2 2 2 1 2 2 2 0 0
2 1 2 2 2 2 2 2 2 0 0
2 1 2 2 0 0 0 0 0 0 0
2 1 2 2 0 0 0 0 0 0 0
2 2 2 2 0 0 0 0 0 0 0

```

Note de lack of notch in the bottom edge of the wall (a 4x4 entity wouldn't be able to fit in there) and presence of a notch in the top edge of the wall (where a 4x4 can fit).
> 2 votes

---
Tags: java, path-finding
---


# Question
Title: Match-3 should pieces store their location in the matrix?
I'm making a match-3 game. I have a TileManager script which stores all the tiles in a matrix, it's a singleton and it handles tile swapping and basicly everything regarding the management of tiles.

I have a variable called selectedTile. I have a method called SwapSelected which swaps the currently selected tile with the one you just clicked on. As pieces don't know their location in the matrix I can only loop through the whole thing to find them but it feels extremly stupid I just feel like there's gotta be a better way. If pieces stored their location and I kept that updated all the time that'd feel stupid too.

What could I do to make this method work nicer and more optimalized? Is there a way or there is no problem with how I do it?

```
    public void SwapSelected(Tile tileToSwap)
    {
        Vector3 tempPos = selectedTile.transform.position;
        selectedTile.transform.position = tileToSwap.transform.position;
        tileToSwap.transform.position = tempPos;

        Vector2Int tileToSwapPosition = new Vector2Int(-1, -1);
        Vector2Int selectedTilePosition = new Vector2Int(-1, -1);

        //OPTIMALIZE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        for (int x = 0; x < _tileMap.GetLength(0); x++)
            for (int y = 0; y < _tileMap.GetLength(1); y++)
            {
                if (_tileMap[x, y] == tileToSwap)
                {
                    tileToSwapPosition = new Vector2Int(x, y);
                }
                if (_tileMap[x, y] == selectedTile)
                {
                    selectedTilePosition = new Vector2Int(x, y);
                }
            }

        _tileMap[selectedTilePosition.x, selectedTilePosition.y] = tileToSwap;
        _tileMap[tileToSwapPosition.x, tileToSwapPosition.y] = selectedTile;

        UpdateTileName(tileToSwap);
        UpdateTileName(selectedTile);
    }

```

# Answer
One optimization pops into my head. Don't use 2D arrays. You can do JUST fine on 1D array, also you can remove one for loop from it, in the long run improve cache hit ratio, making your code possibly faster. What I mean is this:

```
public void SwapSelected(Tile tileToSwap, uint Width)
{
    Vector3 tempPos = selectedTile.transform.position;
    selectedTile.transform.position = tileToSwap.transform.position;
    tileToSwap.transform.position = tempPos;

    uint tileToSwapPosition = UINT_MAX;
    uint selectedTilePosition = UINT_MAX;

    for (uint index = 0; index < _tileMap.length; ++index)
    {
        if (_tileMap[index] == tileToSwap)
        {
            tileToSwapPosition = index;
        }
        if (_tileMap[index] == selectedTile)
        {
            selectedTilePosition = index;
        }
    }

    _tileMap[selectedTilePosition] = tileToSwap;
    _tileMap[tileToSwapPosition] = selectedTile;

    UpdateTileName(tileToSwap);
    UpdateTileName(selectedTile);
}

```

Of course, if this runs fine, which I hope it does, you should not care that much about optimizing the code. Of course, optimal and fast-running code is ESSENTIAL, but not in spite of progress. So don't bog down on this too much, develop great games, and when this becomes a bottleneck then optimize, optimize, optimize :) Have fun man!

EDIT: As per curiosity @DMGregory started in me I ran a benchmark, found here: https://stackoverflow.com/questions/597720/what-are-the-differences-between-a-multidimensional-array-and-an-array-of-arrays/597790#597790

Here are the results:

```
citrus at spaceship in ~/Desktop/Projects/csharpbenchmark
$ mono Main.exe
Jagged:   8.721   7.068   6.361   7.106   7.827   7.821   8.969   7.148   7.427  11.016
Multidimensional:  10.204  12.013   8.750   8.861   9.101   9.978   9.439   8.442   8.843   8.873
Singledimensional:   6.670   4.661   4.326   4.369   4.602   6.469   4.678   4.684   4.451   4.473

citrus at spaceship in ~/Desktop/Projects/csharpbenchmark
$ mono --version
Mono JIT compiler version 6.8.0.105 (tarball Tue Feb  4 20:29:35 GMT 2020)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
TLS:
SIGSEGV:       altstack
Notification:  kqueue
Architecture:  amd64
Disabled:      none
Misc:          softdebug
Interpreter:   yes
LLVM:          supported, not enabled.
Suspend:       hybrid
GC:            sgen (concurrent by default)

```

I did not try this with Unity's mono implementation, as I am pretty sure it differs a touch. But vanilla mono shows, that the single dimensional arrays are faster a bit.
> 0 votes

---
Tags: unity, algorithm, matrix
---


# Question
Title: How to sort polygons without a depth buffer
Please help me getting understanding how did they sort polygons in old games from the eighties.

They did not use z-buffer or anything like this, thats for sure.

Please look at the screenshot. How would one decide that the green surface should be drawn after the table polygons?

The center of the table surface is closer to the viewer from object center, closest vertex point of view. The green surface has the farthest Z. Oh, this big gray table is not split into smaller polygons.

How did they know to draw the green poly after the big gray table surface?

# Answer
> 2 votes
In interview, Ian Andrew, founder of Incentive Software, designer and co-creator of Freescape along side his brother Chris, said:

> Each element was held within a bounding box which enabled the z-order to be completed with one check rather than the thousands involved for each pixel. And Chris used a unique sorting system which really enabled the game to become reality.
>
> (...)
>
> Memory restrictions and speed were the main problems. (...) There was no memory for z-buffering so the object sorting helped speed things up.
>
> (...)
>
> Memory was re-used wherever possible; for example, the back buffer, where the next screen image is constructed, was used during the calculations and object sorting before the drawing even started,

*Apparently they called this technique "box sorting" internally. I have not found more details on how that worked.*

---

What follows is my speculation on my part based on that simple description.

You could define a 3D bounding box for each object. Provided that you never allow bounding boxes to overlap in space, sorting these bounding boxes should be enough to decide the draw order.

To be clear, the following should not be allowed:

The algorithm I describe here, cannot handle that.

You could proceed to project to the view-port the coordinates of the bounding boxes, resulting in some 2D polygons. You could then intersect the 2D polygons from two objects to decide if you need bother to determinate the draw order between two object at all…

If you do, you got to check the depth of the objects at one of the points in the intersection of the 2D polygons, that is one of the points where they visually overlap. The depth for that point would be computed from the distance to the camera, for the other object you would need to solve the intersection of the ray with bounding box. That difference in depth should be enough to decide what object draw first.

*I suppose you would optimize this algorithm further.*

---

For the example case in the question, let us imagine some bounding boxes. I draw them in blue an purple below:

*Caveats: I have no idea if the green square has height, I have no idea if the table is one single bounding box.*

We can intersect the 2D polygons these bounding boxes made in 2D. And in doing so, we find that there there is visual overlap. I mark the visual overlap region in blue below:

While, yes, you would have used depth while projecting each point to 2D (in order to archive perspective), no comparison in depth is done. I repeat that this overlap is entirely visual. *By which I mean, it exists only in 2D, it is the intersection of 2D polygons.*

And thus you would have to compare depth at one of the points in the intersection. Market below, also in blue (added arrows for clarity):

And comparing depth at any of those points would result in the green shape being drawn on top of the table. *You only need to compare depth at one of those. Just one depth check (comparison).*

*Any point that belongs to an intersection of the 2D polygons that are the projections of the bounding boxes of the 3D objects will do, given that those bounding boxes do not intersect in 3D space.*

---
Tags: 3d, rendering, software-rendering, sorting
---


# Question
Title: How i can detect a single ARuco marker among several markers?
Hi everyone i am working on a rehabilitation application that depends on ARuco markers. The idea is to draw an object on a single marker among the four existing ones, then when the patient's hand reaches that marker, the object moves to the next marker, till finishing the exercise. I tried to do so via checking the marker id, and drawing only on it but it remains draw on all of them at the same time, here is the code:

```
// Detect markers
    std::vector<int> ids;
    std::vector<std::vector<cv::Point2f> > corners;
    cv::aruco::detectMarkers(image, marker_dict, corners, ids);

    // Draw markers using opencv tool
    cv::aruco::drawDetectedMarkers(mid, corners, ids);

    // Draw markers custom
    for (size_t i = 0; i < corners.size(); ++i)
    {

        // Convert to integer ponits
        int num = static_cast<int>(corners[i].size());
        std::vector<cv::Point> points;
        for (size_t j = 0; j < corners[i].size(); ++j)
            points.push_back(cv::Point(static_cast<int>(corners[i][j].x), static_cast<int>(corners[i][j].y)));
        const cv::Point* pts = &(points[0]);

        // Draw

        if (ids.at(0) == 45) {
            cv::fillPoly(right, &pts, &num, 1, cv::Scalar(255, 0, 0));
        }

```

# Answer
> 1 votes
You're not checking every marker's ID, you're only checking the ID of the first marker in the list. And you're re-checking that one marker when deciding whether to draw *every* marker.

Replace

```
if (ids.at(0) == 45) {

```

with

```
if (ids.at(i) == 45) {

```

to actually check whether *this* marker's ID is 45, before drawing it.

This is a very simple bit of programming that does not require game development expertise to solve (I don't even know C++!) - so you should really brush up on your language fundamentals and visit our general programming sister site StackOverflow for help with stuff like this.

---
Tags: c++, visual-studio, virtual-reality, augmented-reality
---


# Question
Title: C# Increase move speed for spawned objects
I'm making a simple shooter game where the player shoots a projectile at objects that spawn in random locations. I'd like to change the speed of the spawned objects and am having two issues

1. not sure how to call the speed from a separate script. I'm guessing I need to use GetComponent and could use some advice.
2. how do i vary the speed of spawned enemy objects? Ideally it'd be random from a range of 5 to 20

Move Script

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

public class MoveForward : MonoBehaviour
{
  public float speed = 20f;
  public GameObject Trump;
  public GameObject Player;
  private Rigidbody enemyRb;
  // Start is called before the first frame update
  void Start()
  {
    enemyRb = GetComponent<Rigidbody>();
    Player = GameObject.Find("Player");
    this.transform.LookAt(Player.transform);

  }

  // Update is called once per frame
  void Update()
  {
    transform.Translate(Vector3.forward * Time.deltaTime * speed);

  }
}

```

Spawn Manager Script

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

public class SpawnManager : MonoBehaviour
{
  public GameObject Trump;
  private float spawnRange = 60;
  private float startDelay = 2;
  private float spawnInterval = 1.5f;

  // Start is called before the first frame update
  void Start()
  {
    InvokeRepeating("SpawnTrump", startDelay, spawnInterval);

  }

  // Update is called once per frame
  void Update()
  {
   // MoveForward.speed += speedIncreasePerSpawn * spawnCount;
    //spawnCount++;
  }

  void SpawnTrump()
  {
    Instantiate(Trump, GenerateSpawnPosition(), Trump.transform.rotation);
  }
  private Vector3 GenerateSpawnPosition()
  {
    float spawnPosX = Random.Range(-spawnRange, spawnRange);
    float spawnPosZ = Random.Range(-spawnRange, spawnRange);
    Vector3 randomPos = new Vector3(spawnPosX, 0, spawnPosZ);
    return randomPos;

  }
}

```

# Answer
Did you mean to write something like this?

```
public MoveForward prefabToSpawn;
public float minSpeed = 5f;
public float maxSpeed = 20f;

void Spawn()
{
    MoveForward spawned = Instantiate(
                                  prefabToSpawn,
                                  GenerateSpawnPosition(),
                                  prefabToSpawn.transform.rotation);

    spawned.speed = Random.Range(minSpeed, maxSpeed);
}

```

This is a fairly trivial application of methods you can find in the Unity documentation and in beginner guides, so you may want to work through some more tutorials to make sure you've got a good grasp of the basics.
> 0 votes

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


# Question
Title: OnTriggerEnter not working when placed inside Update()
I'm making a scanner that scans the "world" (like a 10 x 10 space), and I'm trying to sense a `GameObject` called pointer.

They both have colliders, they both have triggers, and the scanner has a rigidbody. I have tried the `OnTriggerEnter` method outside of the update, and it worked, but as soon as I put it inside of `Update`, it breaks.

I don't have to worry about being specific on what the scanner is detecting, because those two are the only ones with a collider.

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

public class Scan : MonoBehaviour
{
    public int worldHeight;
    public int worldWidth;

    public bool sensed;

    public bool spaceBar = false;

    void Update()
    {
        if (Input.GetKeyDown("space") && spaceBar == false)
        {
            spaceBar = true;

            sensed = false;

            //brings scanner to top left corner of world
            transform.position = new Vector3(worldWidth / 2 * -0.64f + 0.32f, worldHeight / 2 * 0.64f + 0.32f, -1);

            for (int sizey = 0; sizey < worldHeight; sizey++)
            {
                if (sensed == false)
                {
                    //shifts scanner down
                    transform.position = new Vector3(worldWidth / 2 * -0.64f - 0.32f, transform.position.y, -1);
                    transform.position = transform.position - new Vector3(0, 0.64f);

                    for (int sizex = 0; sizex < worldWidth; sizex++)
                    {
                        if (sensed == false)
                        {
                            //shifts scanner right
                            transform.position = transform.position + new Vector3(0.64f, 0);

                            void OnCollisionEnter2D(Collision2D grid)
                            {
                                //not working ;-;
                                sensed = true;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            spaceBar = false;
        }
    }
}

```

# Answer
Unity will call your `OnTriggerEnter` or `OnCollisionEnter` callback only if it is a member of your type, not a local method buried in another function.

It looks like you might want to use a physics query here instead, like Physics.OverlapBox. This lets you check for overlapping physics objects in a particular volume of space on demand, using layers or trigger query controls to filter what kinds of objects should be detected.
> 3 votes

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


title: Unity 3D platform spawning problems

text:
# Question
Title: Unity 3D platform spawning problems
I'm making an infinite runner game in Unity 3D. I have it so that platforms spawn and move backwards toward the player and they are destroyed once past the player. Over time when the platforms are spawned, the position they're spawned at gets more and more inaccurate. Sometimes they over lap slightly and sometimes there are small gaps in between them. And as the game is continuously played, it gets worse and worse. You can watch the video below to see what I mean. This is the script I use to spawn the object

```
 public GameObject[] objectSpawned;

 public PlatformKiller myPlatformKiller;

 void Start()
 {
     myPlatformKiller = GameObject.Find("PlatformKiller").GetComponent<PlatformKiller>();
 }

 private void Update()
 {
     if (myPlatformKiller.readyForSpawn)
     {
         int rand = Random.Range(0, objectSpawned.Length);
         Instantiate(objectSpawned[rand], transform.position, transform.rotation * Quaternion.Euler (-90f, 0f, 0f));
     }
 }

```

Here is a video so you can see what I'm talking about: https://youtu.be/eASouQlTsqs

Also, I know the exact unit size for each platform is 11.92. I know this because I added a c# script to each one that shows me the vector3 values. There are originally 20 platforms. And to know exactly where to spawn the object I did 11.92\*20 = 238.4. And the first platform is at -4.78. So I subtracted that from 238.4 and got 233.62. So a z position of 233.62 is the correct place to spawn the object. I just wanted to include that in there so you know that the spawner gameobject is in the right place. Please let me know if there is any additional information about this that I can give you. Everything should theoretically work I think, so I seriously have no idea what to do. Thanks for your help!

readyForSpawn is set in my PlatformKiller script shown below:

```
public bool readyForSpawn;

void Update()
{
    readyForSpawn = false;
}

void OnTriggerEnter(Collider target)
{
    if (target.tag == "Floor")
    {
        readyForSpawn = true;
        Destroy(target.gameObject);
    }
}

```

And that script is attached to PlatformKiller Game Object:

# Answer
Your mistake is assuming that time in a game is continuous.

In a perfect world, if we had a sensor that fired the very instant that the first atom of a platform hit the kill box, and that triggered the new platform to be spawned at exactly that instant (or as fast as the speed of light will allow), then your platforms would match up end-to-end, no problem.

But time in games is quantized in steps. So the first frame that your kill box detects a platform touching it, might be 19 milliseconds after the contact actually happened. If we don't account for that "spare change" time between the theoretical moment of contact and the next opportunity our script ran to detect it, we'll end up with gaps.

So, instead, let's make a version of this that's based on space, not time. That should be easier to reason about:

```
 public Transform[] prefabs;
 public Transform latestSpawn; // Set this to the platform closest to the spawner.

 public float spawnDistance = 11.92; // We could also read this from the bounds of the object.

 private void Update()
 {
     float distance = Vector3.distance(latestSpawn.position, transform.position);

     if (distance >= spawnDistance)
     {
         Vector3 spawnPosition = transform.position;
         spawnPosition.z -= distance - spawnDistance; // Advance the platform to close the gap.

         int rand = Random.Range(0, prefabs.Length);

         latestSpawn = Instantiate(
                           prefabs[rand],
                           position,
                           transform.rotation * Quaternion.Euler (-90f, 0f, 0f)
                       );
     }
 }

```

This can still be a little off if the script runs after your platforms have already moved for the frame (because the new platform hasn't yet, so it will try to catch up and overshoot), so adjust it in the script execution order to run before the platform movement.
> 0 votes

---
Tags: unity, platformer, spawning, prefabs
---


# Question
Title: How to scale major and minor radius of a quarter torus
I am dealing with quarter tori as in the image below. My issue is that I need to be able to scale its major radius and minor radius separately using a scale matrix. However, when I use a regular transformation matrix like:

```
    scaleX, 0, 0, 0,
    0, scaleY, 0, 0,
    0, 0, scaleZ, 0,
    0, 0, 0, 1;

```

It scales both radiuses. Is there a way I can do this separately? I can't get my head around how this would be possible? Thank you in advance.

# Answer
To my knowledge, this is not possible using a transformation matrix since matrices represent linear transformations and the transformation you are asking for isn't linear. The answer in this SO question comes to the same conclusion.

However, if you are not bound to matrices, one possible way to approach this is as follows:

You calculate the normal vector from the torus center towards each vertex inside the **major circle plane** (2d subspace). Scaling the major radius is then just translating every vertex by the same amount into the corresponding normal vector direction. Scaling the minor radius is a little bit trickier and you can approach this in several ways. The easiest way I can think of is just picking a random vertex calculate its "major radius" and store it. Now multiply with a regular scaling matrix, which will scale the major and minor radius. Now calculate the new "major radius" of the selected vertex. Determine the difference and undo the scaling into the major radius direction as described before. If you do the minor radius scaling first, you might be able to calculate the difference to the target major radius, which would save you the "undoing step".

As I said before, without being forced to use matrices there are several ways to approach this. The one I described might not be the most elegant and maybe somebody else can show you a better one or you can come up with one yourself.
> 4 votes

---
Tags: transformation, linear-algebra, scale
---


# Question
Title: Is it safe to save data OnApplicationFocus and OnApplicationPause on mobile?
Unity has messages called `OnApplicationPause` and `OnApplicationFocus`. They are called on each `MonoBehaviour` as the user exits/suspends the application.

I have successfully used this to save data in a regular build, but the save never happens when I am in a development build. My guess is that it is doing some extra logging in development builds when the application exits, and runs out of time before the save can occur.

This is the code I am using to save:

```
#if UNITY_IOS || UNITY_EDITOR
    private void OnApplicationFocus(bool focus)
    {
        if (focus)
        {
            EnterApplication();
        }
        else
        {
            ExitApplication();
        }
    }
#endif

#if UNITY_ANDROID && !UNITY_EDITOR
    private void OnApplicationPause(bool pause)
    {
        if (pause)
        {
            ExitApplication();
        }
        else
        {
            EnterApplication();
        }
    }
#endif

private void ExitApplication()
{
    SaveData();
}

```

I am saving my data using a C# FileStream, not PlayerPrefs.

As you have noticed, I am not using `OnApplicationQuit`. This is because I want the application to save as the user backgrounds the app or exits the app. So please keep this in mind before suggesting I use `OnApplicationQuit`. I also believe the results would be the same in terms of failure.

Is it save to auto-save my game state when these methods are called? Couldn't the operating system take control away before the save completes? If it is not safe, is there a more performant solution than periodically auto-saving?

# Answer
> 1 votes
No, it is not safe.

You can see this by building in debug mode. The extra time it takes to log data prevents it from calling these methods before the OS takes back control.

One solution is to implement an auto-save feature that saves on a timer and/or key events.

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


# Question
Title: How do I check if an iOS subscription is active?
How do I check if an iOS subscription is active? Subscriptions are the only type of purchase available; however, there are several subscription lengths. I have scoured the internet, but all I can find is receipt verification.

The following code seems to work for Android:

```
var products = storeController.products.all;
bool subscribed = products.Where(p => p.hasReceipt).Count() > 0;

```

(although I am not sure if it takes the subscription's expiration date into account.)

But this does not work for iOS. How can I check to see if they have a valid iOS subscription?

# Answer
> 1 votes
Unity now has a built in `SubscriptionManager`. You can use it to determine Subscription validity.

https://docs.unity3d.com/Manual/UnityIAPSubscriptionProducts.html

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


# Question
Title: Why does Unity think my RectTransform has changed?
I am working with UI. I want to know when my `RectTransform` changes its position. I am using `transform.hasChanged`:

```
void Update()
{
    if (transform.hasChanged)
    {
        Debug.Log("Updated Position");
        transform.hasChanged = false;
    }
}

```

However, it thinks it has always changed. "Updated Position" is constantly printing out. If I remove and then readd the component while in play mode, the issue resolves itself. However, I don't want to have to do this, as it is very hacky.

I could just throw a bunch of if statements in there to check, but I'd prefer to make use of the build in `transform.hasChanged` property.

How can I check to see if my `RectTransform` has changed its position efficiently and elegantly?

# Answer
> 1 votes
This was a Unity bug, and has since been fixed. Update your version of Unity to resolve.

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


# Question
Title: Unity3D - Despite using Time.deltaTime, my camera and player move faster at higher framerates
I'm pretty new to c# and Unity so I wouldn't be surprised if I had made some stupid mistakes, but as far as I know, I don't think I misused Time.deltaTime. Any help would be greatly appreciated.

Movement Script:

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

public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;

    public float speed = 12f;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    private float crouchMultiplier = 1f;

    private Vector3 velocity;
    private bool isGrounded;
    private bool isCrouched;
    private float velocityDecay = 1f;

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * crouchMultiplier * velocityDecay * Time.deltaTime);

        Debug.Log(Time.deltaTime);

        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        if (Input.GetKeyDown(KeyCode.LeftControl))
        {
            isCrouched = true;
            gameObject.transform.localScale = new Vector3(1, 1f, 1);
        }

        if (Input.GetKeyUp(KeyCode.LeftControl))
        {
            crouchMultiplier = 1f;
            gameObject.transform.localScale = new Vector3(1, 2f, 1);
            velocityDecay = 1;
            isCrouched = false;
        }

        if (isCrouched)
        {
            if (velocityDecay > 0.2f && isGrounded)
            {
                crouchMultiplier = 2.5f;
                velocityDecay *= 0.995f;
            }
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }
}

```

Camera Script:

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

public class MouseLook : MonoBehaviour
{

    public Transform playerBody;
    public float mouseSensitivity = 100f;

    float xRotation = 0f;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }
}
```
</code></pre>

# Answer
> 1 votes
`Time.deltaTime` is not always 100% accurate. It can sometimes be slightly off if the framerate is extremely high or low, or if you have modified `Time.timeScale`

Movement is usually better handled in `FixedUpdate()`. This syncs it with the physics engine and gives a more consistent experience regardless of framerate and timescale.

A good approach is to read input in the `Update()` function but apply motion in the `FixedUpdate()` function. An extremely simple example:

```
float speed = 5;
float horizontalInput = 0;

void Update() {
    horizontalInput = Input.GetAxis("Horizontal");
}

void FixedUpdate() {
    //You can use Time.deltaTime here and Unity will automatically
    //detect that it's in a FixedUpdate and give the appropriate value.
    //Or you can use Time.fixedDeltaTime if you prefer
    transform.position += transform.right * horizontalInput * speed * Time.deltaTime;
}

```

---
Tags: unity, 3d, frame-rate, time
---


title: Unity - Issue with Camera follow script

text:
# Question
Title: Unity - Issue with Camera follow script
I have a camera follow script which is attached to the main camera and it follows the players position and rotation. The player needs to be near the top of the screen. However when I hit play, the player is shown at the center of the screen. This is how it looks in the scene view and this is how it should reflect when I hit play. Here the "y" position is -2 and "x" rotation is 0.

But when I press play, the "y" position is still -2 but "x" rotation changes to -14.9. And the player is shown at the center of the screen and not near the top.

Here is the camera follow script:

```
[SerializeField] Transform target;
public Vector3 defaultDist;
[SerializeField] float distDamp = .1f;

public Vector3 velocity = Vector3.one;

Transform myT;

void Awake()
{
    myT = transform;
}

void LateUpdate()
{
    SmoothFollow();
}

void SmoothFollow()
 {
    Vector3 toPos = target.position + (target.rotation * defaultDist);

    Vector3 curPos = Vector3.SmoothDamp(myT.position, toPos,ref velocity ,distDamp);
    myT.position = curPos ;

    myT.LookAt(target, target.up);
 }
}

```

After I hit play, I want the x rotation to stay at 0 and the player to be shown near the top of the screen. Can someone please help?

# Answer
> 0 votes
`myT.LookAt(target, target.up);` tells the camera to look directly at the target.

A few options:

```
transform.LookAt(target, Vector3.up);
Vector3 rotation = transform.localEulerAngles;
rotation.x = 0; //remove x rotation
transform.localEulerAngles = rotation;

```

or

```
Vector3 lookTarget = target.position;
lookTarget.y = transform.y; //prevents x rotation
transform.LookAt(lookTarget);

```

or

```
//look at a position a fixed distance below the target
Vector3 offset = new Vector3(0, -2, 0);
transform.LookAt(target.position + offset);

```

As an aside, it is completely pointless to do `myT = transform`. You can just refer directly to the transform, which is also easier to read.

---
Tags: unity, camera
---


# Question
Title: unable to see sprite in scene Getting error as floating point precision limitation
I am trying to create game object by dragging image from project window to scene I am getting error as due to floating point precision limitation- it is recommended to bring the world coordinates of game object within smaller range I am following ruby's adventure tutorial in unity learning

# Answer
> 1 votes
This happens when the GameObject is very far away from the world center. Check its transform in the Inspector. The x, y, or z coordinate is probably greater than 100,000 units. You should never position anything this far from the world origin unless you have a good reason to.

---
Tags: unity, 2d, sprites
---


title: Implementing melee combat in pygame?

text:
# Question
Title: Implementing melee combat in pygame?
I've gone about 2 ways for implementing melee attacks however, bboth have major flaws, hoping someone has a simpler answer.

Method 1: Creating a "projectile" that's using an image, then reducing the transparency of said image. Then offsetting the projectile to be at the end of the character sprite then have it kill itself after 10 milliseconds. This works however it does have a draw back that the more I make the image of the projectile transparent at a certain % pygame stops reading it as an image, it will show the rect but will not allow for collision with enemies. Also if you use mask collision instead of direct rect collision, you damage yourself.

Method 2: Much like the first is a rect that is offset in front of the player, if the hit rect of the object collides with the hit rect of the enemy, that's read as a hit. The drawback is if you get too close the mask collision used for the player/enemy sprite is activated and you take damage. Masking cannot be used with this method as it would read the player's sprite as a collision, meaning you hurt yourself to hurt the enemy.

# Answer
For method 1 you could use `pygame.Surface((width,height))`. It works almost like an image but without loading an image. You can use that surface to detect collisions or use its rect for the same purpose. For debugging purposes you can temporarily fill it with the `surface.fill((red, green, blue, [alpha]))` function.
> 1 votes

---
Tags: collision-detection, python, pygame
---


title: Unity - Handling external data files

text:
# Question
Title: Unity - Handling external data files
I'm moving from an old game dev tool to Unity, and wondering how to go about handling external data files.

In my previous program I'd set up external (txt/ini) files like this:

```
[Group1]
Count=1
1=Hello

[Group2]
Count=2
1=lol
2=end

```

Then I would simply reference which group name and line I wanted to pull.

What's the equivalent to this in unity? I see I can import TextAssets but I can't find functions to pull select data from it. Do these exist?

Do I have to split by lines, loop through them all and convert it into groups (lists) manually? What is the standard method for doing this? Is it moving to xml files?

# Answer
It's generally better to use ScriptableObject assets rather than text files.

For example,

```
[CreateAssetMenu(fileName="Level Data", menuName="Level Data")]
public class LevelAsset : ScriptableObject {
    [Range(60, 300)]
    [SerializeField] private float duration;
    [Range(1, 20)]
    [SerializeField] private int obstacles;

    public float Duration => duration;
    public int Obstacles => obstacles;
}

```

This adds a new entry called "Level Data" to the "Create" menu (right-click in the Project panel and choose Create, or go to Assets \> Create in the menu. Selecting this entry will create a new asset file which you can edit in the Inspector.

You can create as many assets of this type as you wish, and reference them from your scripts.

The GUI-driven interface in the Inspector is safer and easier to use than manually created text files. As you can see in the example, it's type-safe and you can even apply constraints such as `[Range()]`. When needed, you can even create your own Editors which override the default inspector appearance.
> 1 votes

---
Tags: unity, data
---


# Question
Title: Sprites not being destroyed when interacted with
I am creating a simple platformer where the enemies die when jumped on; I am calling a method from my enemyController

```
public void Hurt()
{
    Destroy(this.gameObject);

}

```

The console says this when I jump on them:

> MissingReferenceException: The object of type 'Enemy' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. Enemy.Hurt () (at Assets/Scripts/Enemy.cs:48) CharacterController2D.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/CharacterController2D.cs:188)

The script that references the method is in my characterController

```
    private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Enemy")
    {
        foreach(ContactPoint2D point in collision.contacts)
        {
            Debug.Log(point.normal);
            Debug.DrawLine(point.point,point.point+point.normal, Color.yellow, 10);
            if(point.normal.y >= 0.6f)
            {
                Vector2 velocity = rb2d.velocity;
                velocity.y = jumpForce;
                rb2d.velocity = velocity;
                enemy.Hurt();
            }
            else
            {
                rb2d.AddForce(new Vector3(-transform.position.x,jumpForce, transform.position.z));
                Hurt();
                animator.SetBool("isHit", true);
            }
        }

```

It checks whether the player is above the enemies and if so it destroys them; if not the player takes damage and is knocked back(The knockback is not yet implemented). Why do my enemies not get destroyed. They are not spawned in via script

# Answer
> 1 votes
In your `OnCollisionEnter2D()` function, you have this line of code:

```
enemy.Hurt();

```

You don't set the value of `enemy` anywhere in that function. It's likely that `enemy` is always pointed at the same enemy, so each time you call `Hurt()` it's actually on the same enemy (not necessarily the one you collided with) and thus `Hurt()` is getting called on the same enemy more than once.

It should probably look like this:

```
private void OnCollisionEnter2D(Collision2D collision) {
    if (collision.gameObject.tag == "Enemy") {
        var enemy = collision.gameObject.GetComponent<Enemy>() //You need this line!
        foreach(ContactPoint2D point in collision.contacts) {
            if(point.normal.y >= 0.6f)
            {
                Vector2 velocity = rb2d.velocity;
                velocity.y = jumpForce;
                rb2d.velocity = velocity;
                enemy.Hurt();
            }
        //etc etc

```

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


# Question
Title: How do I get current emission intensity of a material in code?
I'm unable to find how can I get current intensity level of emission in Unity.

Is there some kind of method that can return its value?

I need it to complete my algorithm's formula:

```
current_color = (intensity * 10)/20;

```

# Answer
Depending on what you mean by "Intensity", here are a couple of options:

```
// This gives you the multiplier applied to the colour,
// assuming the source colour had its greatest component set to 1
static float GetEmissionMultiplier(Material mat) {
    var colour = mat.GetColor("_EmissionColor");
    return Mathf.Max(colour.r, colour.g, colour.b);
}

// This gives the perceived luminance of the emissive colour,
// accounting for the fact that green is brighter than blue,
// and yellow (red + green) is brighter than green, etc.
// Coefficients via https://en.wikipedia.org/wiki/Luma_(video)
static float GetEmissionLuminance(Material mat) {
    var colour = mat.GetVector("_EmissionColor");
    return Vector4.Dot(colour, new Vector4(0.2126f, 0.7152f, 0.0722f, 0.0f));
}

```
> 1 votes

---
Tags: unity, c#, rendering, materials
---


# Question
Title: How to restart game from end screen, rather than resume the previous game state?
Video as you can see there I am trying to make my end screen restart my game but whats happening is that ***its not restarting my game its just loading the same thing when I die*** \>\> how could I make it so it restarts my game when I click start game on my end screen?

my end screen def

```
---------------------------------------------------

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(window, ac,(x,y,w,h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(window, ic,(x,y,w,h))
    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    window.blit(textSurf, textRect)

#------------------------------------------------------

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def endScreen():
    red = (200,0,0)
    green = (0,200,0)
    bright_red = (255,0,0)
    bright_green = (0,255,0)

    intro = True
    while intro:
        for event in pygame.event.get():
            #print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        window.fill((255,255,255))
        largeText = pygame.font.Font('BLOODY.ttf',100)
        TextSurf, TextRect = text_objects("You Have Died Fool", largeText)
        TextRect.center = ((800/2), (800/2))
        window.blit(TextSurf, TextRect)
        button("Start Game",150,450,100,50,green,bright_green,game_loop)

# make the square brighter if collideded with the buttons
        mouse = pygame.mouse.get_pos()
        if 150+120 > mouse[0] > 150 and 450+50 > mouse[1] > 450:
            pygame.draw.rect(window, bright_green,(150,450,120,50))
        else:
            pygame.draw.rect(window, green,(150,450,120,50))
        if 550+110 > mouse[0] > 550 and 450+50 > mouse[1] > 450:
            pygame.draw.rect(window, bright_red,(550,450,110,50))
        else:
            pygame.draw.rect(window, red,(550,450,110,50))
# ---------------------------------------------------------------------

        smallText = pygame.font.Font("freesansbold.ttf",20)
        textSurf, textRect = text_objects("Start Game", smallText)
        textRect.center = ( (150+(120/2)), (450+(50/2)) )
        window.blit(textSurf, textRect)

        smallText = pygame.font.Font("freesansbold.ttf",20)
        textSurf, textRect = text_objects("Quit Game", smallText)
        textRect.center = ( (150+(910/2)), (450+(50/2)) )
        window.blit(textSurf, textRect)

        pygame.display.update()
        clock.tick(15)

#----------------------------------------------------------

```

and on my main loop I said if my playerman health is \> -1 it should load the end screen

            if playerman.health < -5:
                endScreen()

```

# Answer
> 0 votes
You can have a boolean variable like `playing` that you set to `True` when you enter the game. Then, when you load the endscreen you set it to `False`. Then, when you press the try again button, set it back to `True` to enter the loop again.

---
Tags: python, pygame
---


# Question
Title: A ball hits the corner slightly, where will it deflect?
I am currently making an iOS Game but I have a small problem.
The game is simply a ball which you can control to avoid obstacles and find the food. When the ball hits, e.g. the top or the bottom of an obstacle, it's easy, the y-speed is just inverted. Same with left and right, where the x-speed is inverted.
But what happens when the mass point of the ball doesn't touch a side of the obstacle, but its surface is? Where will it be deflected? What's the maths behind that?
Here's an image to illustrate the problem:

Thanks in advance for help!

# Answer
You can't just "flip velocity over y". To further that point, its obvious to see on the left and right sides of the box you would not flip over y, but instead flip over x.

On the corners you need to flip over a diagonal direction. This is where it becomes less obvious how to flip it. But it's still quite easy:

What you need is a function to flip over any direction. This is often referred to as a reflect function. This direction we call the normal, n.

On the top: n = (1, 0)

On the bottom: n = (-1, 0)

On the left: n = (-1, 0)

On the right: n = (1, 0)

On the corners: n = normalize(circle center - corner), this is the direction between the center of the circle and corner of the box, you must determine which corner to use

Now you have n. Here's how to reflect velocity over n:

```
reflect(vec2 vec, vec2 n)
    // First project vec onto n, this gives the length of vec along the n axis
    float nLength = dot(vec, n)
    // Lets get that as a vector along n
    vec2 vecN = nLength * n
    // Now we want to know how much of vec is going along tan/perpendicular to n, easy, just remove vecN from vec
    vec2 vecTan = vec - vecN
    // These two should sum together such that vec = vecN + vecTan, but we actually want to flip the tangent/perpendicular part of vec, so negate
    vec2 results = vecN - vecTan
    return results

```
> 1 votes

---
Tags: physics, ios, simulations, swift
---


title: Visual Studio Code can't see Unity API?

text:
# Question
Title: Visual Studio Code can't see Unity API?
I followed the official step-by-step "**Visual Studio Code and Unity**" guide, but it seems I messed up something, because **Intellisense doesn't see any Unity related stuff**.

Like the **MonoBehaviour** class and its members (like **.transform**), or the Unity callbacks, like **Start** or **Update**.

# Answer
> 1 votes
***Well, the source of this issue changes from issue to issue. So if this doesn't solve your issue, be sure to read further down below.***

In my case it was due to **changing the default install path for new applications**.

I changed the default install path to my HDD, so I don't have to manually change every new application's install path from my SSD to my HDD.

The problem is that some applications **only looks** at the drive on which **Windows is installed**.

So now I change my **default install path to my SSD** every time I update Unity, so Visual Studio will be installed at the path where **VS Code will look for the dlls**.

But sometimes **this won't be enough**, for example this time I wasted some time again, and still haven't figured out the correct way of doing this. Maybe I will just give in, and always manually change the install path. What I did:

* I had to uninstall Unity, Visual Studio, restart my computer
* Then install Unity, Visual Studio, restart my computer,
* **In Unity \> Preferences, switched the IDE to Visual Studio.**
* **Opened the a file, which opened Visual Studio.**
* **Switched the IDE to Visual Studio Code.**
* Works.

**Update:**

* I've just uninstalled my old Unity, and installed the new one, and as it turns out, a Visual Studio reinstallation, and restarts **aren't needed**.
* **Just open a file with Visual Studio as an IDE, and then switch to Visual Studio Code.**

# Answer
> 2 votes
On a newly created project, opening a C# script via double clicking it won't correctly load VSCode's extensions. (this is due to parts of the sln file not being generated.)

Create at least one C# script, then go to 'Assets' \> 'Open C# Project' will generate the correct sln file and after a quick reload of VSCode, intellisense starts working.

After doing this one time, intellisense will continue to work as expected, double clicking C# scripts etc.

# Answer
> 0 votes
I had the same problem when I started using unity and visual studio. Here's how I got around it: to open a c# file from unity, what most people do is double click on the script. the problem with this for me, was that it only opened the file, not the c# project. So, make sure you've opened the c# file by double clicking before, and then, in visual studios, click **File-Open Project/Solution** and then navigate to the folder you've saved your unity project in. In that folder, there should be a C# project file.(if there isn't, just double click on the script in unity, close the script, and try to open the project file again.) open it, and voila! If your having the same problem i was, intellisense should be working with unity!

I hope this was helpful.

# Answer
> 0 votes
It's not a new issue. I just faced such a problem and mostly that's because Unity and VS or other IDEs are not synced. Sometimes even going to Preferences and setting the chosen IDE even doesn't work. C# classes are known as miscellaneous and auto-complete can't find the right choices.

Sometimes it's because you use a cracked version of VS or Unity or just downloaded them from an unofficial source.

Most of the time I choose the last solution first. Just remove both VS and Unity and download them from their official website. From the time I used official versions I just don't face such problems.

# Answer
> 0 votes
1. Open VSCode
2. Uninstall all C# extensions you have installed (Only to avoid conflicts with new extensions)
3. File -\> Open Folder -\> (Select your unity project folder)
4. VSCode will automatically install the required extensions.
5. Start typing in your code.
6. I'm attaching the snapshot of my VSCode working with my unity mini-project.

Hope this helps you.

---
Tags: unity, visual-studio-code
---


title: Rotating Cannon's Mouth Toward Player

text:
# Question
Title: Rotating Cannon's Mouth Toward Player
I am trying to make my cannon mouth rotate towards player, but the rotation is messed up and up I don't know how to fix it.

```
class enemyshoot:
    def __init__(self,x,y,height,width,color):
    # [...............]
         self.look_at_pos = (x,y)

 def draw(self):
      # [............]
        self.rect = self.shootsright.get_rect(topleft = (self.x, self.y))

        dx = self.look_at_pos[0] - self.rect.centerx
        dy = self.look_at_pos[1] - self.rect.centery
        angle = (180/math.pi) * math.atan2(-dy, dx)
        self.image = pygame.transform.rotate(self.shootsright, angle)
        self.rect  = self.image.get_rect(center = self.rect.center)

    def lookAt( self, coordinate ):
        self.look_at_pos = coordinate

```

My full enemyshoot class

```
shotsright = pygame.image.load("canss.png")
class enemyshoot:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y =y
        self.height = height
        self.width = width
        self.color = color
        self.health = 10
        self.hitbox = (self.x + -20, self.y + 30, 31, 57)
       #-------------------------------------------------------
        # Make a Reference Copy of the bitmap for later rotation
        self.shootsright = pygame.image.load("canss.png")
        self.shootsright = pygame.transform.scale(self.shootsright,(self.shootsright.get_width()-150,self.shootsright.get_height()-150))
        self.image    = self.shootsright
        self.rect     = self.image.get_rect()
        self.position = pygame.math.Vector2( (x, y) )
        self.isLookingAtPlayer = False
        self.look_at_pos = (x,y)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        window.blit(self.image, self.rect)
        self.rect = self.shootsright.get_rect(topleft = (self.x, self.y))

        dx = self.look_at_pos[0] - self.rect.centerx
        dy = self.look_at_pos[1] - self.rect.centery
        angle = (180/math.pi) * math.atan2(-dy, dx)
        self.image = pygame.transform.rotate(self.shootsright, angle)
        self.rect  = self.image.get_rect(center = self.rect.center)

        # ------------
        self.hits = (self.x + 20, self.y, 28,60)
        pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 60, 100, 10)) # NEW
        pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 60, 100 - (5 * (10 - self.health)), 10))
        self.hitbox = (self.x + 200, self.y + 200, 51, 65)
    def lookAt( self, coordinate ):
        self.look_at_pos = coordinate

black = (0,0,0)
enemyshooting = []
platformGroup = pygame.sprite.Group
platformList = []
level = ["                                                                                p               p           p                         p                        p        ",
         "                                       ",
         "                             ",
         "                                      ",
         "                                  ",
         "                           ",
         "                                      ",
         "                                      ",
         "                                    ",
         "                                   ",
         "                    ",]
for iy, row in enumerate(level):
    for ix, col in enumerate(row):
        if col == "p":
            new_platforms = enemyshoot(ix*10, iy*50, 10,10,(255,255,255))
            enemyshooting.append(new_platforms)

```

This is where the cannons rotate towards the player, wherever they are

```
        for enemyshoot in enemyshooting:
            if not enemyshoot.isLookingAtPlayer:
                enemyshoot.lookAt((playerman.x, playerman.y))

```

# Answer
> 1 votes
I don't think this will fix the issue, but on the for loop you should add `enemyshoot.isLookingAtPlayer = True` to make sure you do not rotate it when it is not needed.

It would look like this

```
        for enemyshoot in enemyshooting:
            if not enemyshoot.isLookingAtPlayer:
                enemyshoot.lookAt((playerman.x, playerman.y))
                enemyshoot.isLookingAtPlayer = True

```

# Answer
> 0 votes
Try using vectors and vector math instead of your own equations:

```
delta = Vec2d(self.look_at_pos) - self.rect.center
angle = delta.get_angle()

```

Also make sure cannon image is looking right (literally).

---
Tags: python, transformation, pygame
---


# Question
Title: How to detect if object is moving in clockwise- or counterclockwise direction?
I've read this one, but I need more info: rotating an object from sourceAngle to destAngle, both 0-359, clockwise or counter clockwise?

I have a ball. The user is able to drag the ball in any direction clockwise/anticlockwise around a circle. I need to know whether or not the ball was dragged clockwise or anticlockwise.

I'd like to get both vector/non-vector methods.

# Answer
> 12 votes
Keep track of the position of the ball on the previous frame. Then let's say we have:

```
C
|\                // C = Rotation Center
| \               // P1 = Previous Frame Position
|  P2             // P2 = Current Frame Position
P1

```

You need to check using the 2D analog of a cross product whether P2 lies to the left or to the right of the C-P1 line segment. If it's to the right, then it's rotating clockwise. If it's to the left, then it's rotating counter-clockwise.

You can use this method to check:

```
bool isLeft(Vector2 c, Vector2 p1, Vector2 p2)
{
     return ((p1.x - c.x)*(p2.y - c.y) - (p1.y - c.y)*(p2.x - c.x)) > 0;
}

```

# Answer
> 3 votes
Given the points `Source`, `Destination` and `Centre`, where a move has happened from `Source` to `Destination` first compute the vectors:

```
CentreSource = Source - Centre
CentreDestination = Destination - Centre

```

Compute the dot product of the tværvector of `CentreSource` and `CentreDestination`:

```
RorL = CentreSourceX * CentreDestinationY - CentreSourceY * CentreDestinationX

```

Now `RorL` should be positive if the point is moving counterclockwise around the centre, negative in case of clockwise, and `0` if the move was either 0 or 180 degrees.

You can further check if the move was above or below 90 degrees by computing the dot product of `CentreSource` and `CentreDestination`:

```
AorB = CentreSourceX * CentreSourceY + CentreDestinationX * CentreDestinationY

```

If `AorB` is positive then the move was below 90 degrees, if it is negative the move was above 90 degrees, and if it is 0 then the move was either exactly 90 degrees or it either started or ended in the point `Centre`.

# Answer
> 2 votes
How I would achieve this is to have a stack of 3 positions and use these to determine rotation of the object.

example:

```
double[] position = new double[2];

double[][] positions = new double[3][2];
void bool clockwise () {
     for (int i = 0; i < 2; i++) {
          positions[i + 1][0] = positions[i][0];
          positions[i + 1][1] = positions[i][1];
     }
     positions[0][0] = position[0];
     positions[0][1] = position[1];
     double[] averageOfEnds = new double[]{ (positions[0][0] + position[2][0]) / 2, (positions[0][1] + position[2][1]) / 2 };
     if (positions[2][0] < averageOfEnds[0] || positions[2][1] > averageOfEnds[1]) {
          return true;
     }
     return false;
}

```

this assumes you axes are like

```
+
|
|
|
- ------ +

```

# Answer
> 1 votes
Starting with the representation:

```
[x2, y2]' = R(th) * [x1 y1]';
R(th) = [cos(th) -sin(th)
         sin(th)  cos(th)]

```

Which is basically a rotation operation on a vector. x2 and y2 are the rotated position of x1 and y1. The idea is to get cos(th) and sin(th) in terms of x1,x2,y1 and y2 variables. In order not to fall in to wrong quadrant, atan2 is used with the values of sin(th) and cos(th) which boils down to:

```
  x1 = cos(th1); y1 = sin(th1);
  x2 = cos(th2); y2 = sin(th2);

  diff = atan2((x1*y2 - x2*y1), (y1*y2 + x1*x2)); # atan2(Yterm,Xterm) (Matlab notation

```

Derivation:

# Answer
> -1 votes
The easiest solution would be to keep a reference to the object's previous and current or previous, current and extrapolated next positions and do a simple compare.

---
Tags: mathematics, vector, trigonometry
---