# Question
Title: Stride: Can't see shadows in programmatically created scene
As a learning exercise I'm trying to recreate the 'new game' scene with the sphere on a plane. Mostly working but two issues:

* Shadows are not working.
* Skybox light (reflected on the sphere) is not working. I can't see any way to set this texture.

Please tell me what I'm doing wrong. Thanks!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Stride.Core.Mathematics;
using Stride.Input;
using Stride.Engine;
using System.Runtime.CompilerServices;
using Stride.Engine.Processors;
using Stride.Rendering.Compositing;
using Stride.Rendering.Lights;
using Stride.Graphics;
using Stride.Rendering;
using Stride.Graphics.GeometricPrimitives;
using Stride.Extensions;
using Stride.Particles.Updaters.FieldShapes;
using Stride.Rendering.Shadows;
using Stride.Rendering.Skyboxes;

namespace SceneTest
{
    public class Setup : StartupScript
    {
        // Declared public member fields and properties will show in the game studio

        public override void Start()
        {
            // Initialization of the script.
            Scene mainScene = new Scene { Name = "New Scene" };

            // Camera
            Entity cameraEntity = new Entity();
            cameraEntity.Transform.Position = new Vector3(2.6f, 0.6f, -1.0f);
            cameraEntity.Transform.Rotation = Quaternion.RotationY(MathUtil.DegreesToRadians(110.0f));
            CameraComponent camera = new CameraComponent();
            camera.FarClipPlane = 1000.0f;
            camera.NearClipPlane = 0.1f;
            camera.Projection = CameraProjectionMode.Perspective;
            camera.VerticalFieldOfView = 45.0f;
            camera.Slot = SceneSystem.GraphicsCompositor.Cameras[0].ToSlotId();
            cameraEntity.Add(camera);
            cameraEntity.Add(new BasicCameraController());

            mainScene.Entities.Add(cameraEntity);

            // Directional Light
            Entity lightEntity = new Entity();
            lightEntity.Transform.Position = new Vector3(0.0f, 2.0f, 0.0f);
            lightEntity.Transform.Rotation = Quaternion.RotationX(MathUtil.DegreesToRadians(-30.0f)) * Quaternion.RotationY(MathUtil.DegreesToRadians(180.0f)); // * X(-30.0f)
            LightComponent light = new LightComponent();
            LightDirectional directLight = new LightDirectional();

            var shadow = directLight.Shadow as LightDirectionalShadowMap; // new LightDirectionalShadowMap();
            shadow.Enabled = true;
            shadow.Size = LightShadowMapSize.Small;
            shadow.Filter = new LightShadowMapFilterTypePcf();
            shadow.CascadeCount = LightShadowMapCascadeCount.FourCascades;
            shadow.DepthRange.IsAutomatic = true;

            //directLight.Shadow.Enabled = true;
            //directLight.Shadow.Filter = new LightShadowMapFilterTypePcf();
            //directLight.Shadow.Size = LightShadowMapSize.Small;

            light.Type = directLight;
            light.SetColor(Color.White.ToColor3());
            light.Intensity = 20.0f;
            lightEntity.Add(light);
            mainScene.Entities.Add(lightEntity);

            // Skybox
            Entity skyEntity = new Entity();
            skyEntity.Transform.Position = new Vector3(0.0f, 2.0f, -2.0f);
            BackgroundComponent skyBox = new BackgroundComponent();
            skyBox.Texture = Content.Load<Texture>("Skybox texture");
            skyEntity.Add(skyBox);
            LightSkybox lightSkyBox = new LightSkybox();
            var skyBoxT = new Skybox();

            lightSkyBox.Skybox = skyBoxT;
            LightComponent lightSky = new LightComponent();

            lightSky.Type = lightSkyBox;
            lightSky.Intensity = 1.0f;
            skyEntity.Add(lightSky);
            mainScene.Entities.Add(skyEntity);

            // Ground
            Entity groundEntity = new Entity();
            // Transform is 0
            var plane = GeometricPrimitive.Plane.New(GraphicsDevice,10.0f, 10.0f, 1, 1, 1.0f, 1.0f, false, false, NormalDirection.UpY);
            var meshDraw = plane.ToMeshDraw();
            var mesh = new Mesh { Draw = meshDraw };
            var material = Content.Load<Material>("Ground Material");
            var groundModel = new Model();
            groundModel.Meshes.Add(mesh);
            groundModel.Materials.Add(material);
            mesh.MaterialIndex = 0;
            var groundComponent = new ModelComponent();
            groundComponent.Model = groundModel;
            groundComponent.IsShadowCaster = true;
            groundEntity.Add(groundComponent);
            mainScene.Entities.Add(groundEntity);

            // Sphere
            Entity sphereEntity = new Entity();
            sphereEntity.Transform.Position = new Vector3(0.0f, 0.5f, 0.0f);
            var sphere = GeometricPrimitive.Sphere.New(GraphicsDevice, 0.5f, 30, 1, 1, false);
            var sphereDraw = sphere.ToMeshDraw();
            var sphereMesh = new Mesh { Draw = sphereDraw };
            var sphereMaterial = Content.Load<Material>("Sphere Material");
            var sphereModel = new Model();
            sphereModel.Meshes.Add(sphereMesh);
            sphereModel.Materials.Add(sphereMaterial);
            sphereMesh.MaterialIndex = 0;
            var sphereComponent = new ModelComponent();
            sphereComponent.Model = sphereModel;
            sphereComponent.IsShadowCaster = true;
            sphereEntity.Add(sphereComponent);
            mainScene.Entities.Add(sphereEntity);

            SceneSystem.SceneInstance.RootScene = mainScene;
        }
    }
}
```
</code></pre>

# Answer
If you don't see shadows, you are most probably missing the bounding box for the model, which is required for the shadow map calculations.

The way you generate the models isn't entirely correct. Instead of using the `GeometricPrimitve` directly use the `ProceduralModel` classes which have a `Generate()` method that takes care of setting up everything. Something like:

```
// The model classes
var myModel = new PlaneProceduralModel();
var model = new Model();
var modelComponent = new ModelComponent(model);

// Generate the procedual model
myModel.Generate(Services, model);

```

See also: How to create a mesh in code?
> 0 votes

---
Tags: shadows, skybox, stride
---


# Question
Title: When the scene is loaded again start function is not getting called from the script in which I have applied singleton pattern
In `Game` scene I have an empty `GameObject` Circles to which a script named Circles is attached. The script is:

```
public class Circles : MonoBehaviour
{
    public Text text;
    LevelManager levelManager;
   public int score=0;
    int enemyNo;
  private void Awake()
    {
        int scorer = FindObjectsOfType<Circles>().Length;
        if (scorer > 1)
        {
            gameObject.SetActive(false);
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }

    }
 void Start()
    {

        print("start");
        enemyNo = Random.Range(0, 4);
        Invoke("instantiator", 1.5f);

        text.text = score.ToString();
        levelManager = FindObjectOfType<LevelManager>();

    }
}

```

When the player loses he goes to `GameOver` scene where his score is displayed. When the player presses play again button then he comes to `Game` scene again and the start function is not getting called. When the player presses the play again button I want to destroy previously existing Circles `GameObject` and not the `GameObject` Circles which is present in the scene so that score is set to zero and the start function get called. How to fix this issue?

# Answer
i have figured out the solution for this question. In the Circles script which is provided in the question I have added these lines of code:-

```
 void OnEnable()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    void OnDisable()
    {
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        // here you can use scene.buildIndex or scene.name to check which scene was loaded
        if (scene.name == "GameOver")
        {

            // Destroy the gameobject this script is attached to
            Destroy(gameObject);
        }
    }

```

And everything is working just as I wanted.
> 3 votes

---
Tags: unity
---


title: Ray-Box (AABB) is slower than without

text:
# Question
Title: Ray-Box (AABB) is slower than without
I'm trying to write my own ray tracer. The last days I tried implementing a bounding box algorithm for it. But I'm getting a much slower frame rate with the bounding boxes turned on. I think it has something to do with checking the box with every ray but I don't know how I could change that.

Here is my code for the intersection algorithm:

```
bool Intersect(Ray r, float3 lb, float3 rt)
{
    float3 dir_inv = 1 / r.direction;

    double t1 = (lb[0] - r.origin[0]) * dir_inv[0];
    double t2 = (rt[0] - r.origin[0]) * dir_inv[0];

    double tmin = min(t1, t2);
    double tmax = max(t1, t2);

    for (int i = 1; i < 3; ++i)
    {
        t1 = (lb[i] - r.origin[i]) * dir_inv[i];
        t2 = (rt[i] - r.origin[i]) * dir_inv[i];

        tmin = max(tmin, min(t1, t2));
        tmax = min(tmax, max(t1, t2));
    }

    return tmax > max(tmin, 0.0);
}

```

My trace function:

```
RayHit Trace(Ray ray)
{
    RayHit bestHit = CreateRayHit();
    uint count, stride, i;

    // Trace ground plane
    IntersectGroundPlane(ray, bestHit);

    // Trace spheres
    _Spheres.GetDimensions(count, stride);
    for (i = 0; i < count; i++)
    {
        if (Intersect(ray, _Spheres[i].position - (_Spheres[i].radius), _Spheres[i].position + (_Spheres[i].radius)))
            IntersectSphere(ray, bestHit, _Spheres[i]);
    }

    // Trace mesh objects
    _MeshObjects.GetDimensions(count, stride);
    for (i = 0; i < count; i++)
    {
        //if (Intersect(ray, float3(0.0f, 0.0f, 0.0f), float3(10.0f, 10.0f, 10.0f)))
            //IntersectMeshObject(ray, bestHit, _MeshObjects[i]);
    }

    return bestHit;
}

```

# Answer
> 2 votes
It looks like you're using the bounding boxes on sphere primitives.

A sphere intersection is *very* cheap, as computer graphics operations go. In fact, it's often substantially *cheaper* than testing against a bounding box (one slightly more complicated check instead of 3 simple ones), so using a bounding box to save sphere checks is rather like taking out $100 of insurance on a $20 trinket.

For every ray that misses the sphere, you end up paying the bounding box test cost, which is more expensive than testing the sphere directly. And for every ray that hits the sphere (ore misses but comes close enough to hit the box), you pay both the bounding box test cost *and* the sphere test cost.

Where bounding box checks can help you are...

* Situations where the check it lets you skip is much more expensive than a simple box (like a triangle mesh or implicit surface)
* Situations where a bounding box test rejection lets you skip a whole bunch of objects (like if you had a group of spheres or other primitives in a single bounding box for the whole collection, or using a hierachical space partition that lets you skip whole swaths of your scene)

---
Tags: hlsl, bounding-boxes, intersection, raytracing
---


title: Plane to always face object

text:
# Question
Title: Plane to always face object
How do i get a plane to always face an object with the flat/mesh/xy side? I tried sticking in Vector3. forward and up but i always get the plane facing the object on an edge.

```
    void Update()
{
    planeRotate.transform.LookAt(cube.transform, );
}

```

# Answer
> 1 votes
The face of a plane primitive points in its local "up" direction (y+), not the local "forward" direction (z+) used by `LookAt`.

So you want a rotation that takes the y+ axis to point toward the target:

```
Vector3 directionToTarget = cube.transform.position - planeRotation.transform.position;
planeRotation.transform.rotation = Quaternion.FromToRotation(Vector3.up, directionToTarget);

```

If you have a preferred "twist" direction you want the z+ axis to face, you gan enforce that like so:

```
Vector3 zTarget = Vector3.up;

Quaternion zToTarget = Quaternion.LookRotation(directionToTarget, -zTarget);
Quaternion yToZ = Quaternion.Euler(90, 0, 0);

planeRotation.transform.rotation = zToTarget * yToZ;

```

---
Tags: rotation, quaternion
---


# Question
Title: PyBullet & OpenGL - Rotations are reversed in OpenGL
Project description: I am writing a basic game engine to help with my PhD topic on multi-agent learning. I am using PyBullet as the backend physics engine and OpenGL for visual display. I have OpenGL buffers set up to hold the object information such as position(vec3) and rotation(matrix4x4) with rotations being done using Quaternions, but are stored using Euler angles for convenience.

My problem is that when I rotate an object in the OpenGL game world (around any axis), the pyBullet rotation (as seen from the pyBullet GUI) is in the opposite direction and sometime completely off. I must be missing something quiet basic and I apologies if this is a simple fix. I have also provided a video to show the issue that I am having - link to video of error (Link to video):

When I extract the rotation from PyBullet using `getBasePositionAndOrientation()` and convert the quaternion to Euler angles using `pybullet.getEulerFromQuaternion()`, the result is the correct vec3, but upon conversion to the rotation matrix `pybullet.getMatrixFromQuaternion()`, it seems to reverse the rotation direction.

Please see my code below:

```
'obj = Class BaseSceneObject'
'action = Euler rotation angle in degrees to apply vec3(x, y, z) e.g.(1., 0., 0.) apply +1 degree rotation to x-axis'

'Collect current position and rotation of object and update PyBullet'
# get the rotation - euler angles in degrees vec3(x,y,z)
rot = obj.get_rotation()
# add rotation action (e.g. +1 degree to x = vec3(1., 0., 0.)) and convert to radians
rot = math.radians(rot[0] + action[0]), math.radians(rot[1] + action[1]), math.radians(rot[2] + action[2])
# convert rotation from euler to quaternion
quat = pybullet.getQuaternionFromEuler(rot)
# update position and orientation
pybullet.resetBasePositionAndOrientation(bodyUniqueId=obj.get_rigid_body_id(),
                                         posObj=obj.get_position(),
                                         ornObj=quat)

'Collect PyBullet results and update OpenGL'
# get position and rotation from PyBullet
position, rotation = pybullet.getBasePositionAndOrientation(bodyUniqueId=obj.get_rigid_body_id())
# update object position
obj.set_position(position=position)
# convert rotation quaternion to euler angles
rot_r = pybullet.getEulerFromQuaternion(rotation)
# convert radians to degrees
rot_d = math.degrees(rot_r[0]), math.degrees(rot_r[1]), math.degrees(rot_r[2])
# construct OpenGL object rotation matrix
rot_m_final = numpy.identity(4)
rot_mr = numpy.array(pybullet.getMatrixFromQuaternion(rotation)).reshape(3, 3)
rot_m_final[:3, :3] = rot_mr
# update OpenGL rotation matrix
obj.set_rotation(rotation=rot_d,
                 rotation_matrix=rot_m_final)

```

Thank you for reading this and I hope that you can help me.

# Answer
It turns out that the above code is correct. The issue resided in the OpennGL shader, where I forgot that matrix calculations are non commutive, i.e. `numpy.matmul(Mat4(Rotation), Vec4(position))` is not the same as `numpy.matmul(Vec4(position), Mat4(Rotation))`.

After updating my shader code from:

```
vec4 aRPos = vec4(aRotation * aVertex);

```

To:

```
vec4 aRPos = vec4(aVertex * aRotation);

```

It worked perfectly. Thank you.
> 2 votes

---
Tags: opengl, graphics, rotation, python, bullet-physics
---


# Question
Title: How to set off Cinemachine camera shake during an explosion
How do I set up camera shake during an explosion with Cinemachine? This is the first time that I've messed with the impulse listener on cinemachine and so far, I can only get the camera to shake when the an object makes a collision with the object that the 'Cinemachine Collision Impulse Source' component is attached to(in my case, a Grenade). I want to set it up so that the camera will only shake at the moment the grenade explodes(Because my Grenade script has a countdown timer before it explodes, it does not just explode upon collision).

# Answer
From the docs:

> Use the **Cinemachine Impulse Source** component to generate impulses on events that are not collisions or Collider triggers. This is a generic Impulse Source that exposes a family of GenerateImpulse() API methods. These methods generate impulses at the specified locations and with the specified velocities and strengths. Call these methods directly from your game logic, or use them with UnityEvents.

So, place an Impulse Source component somewhere in your scene. It can be part of the explosion effect prefab you spawn on demand, or a persistent scene object that you trigger at the same time you spawn the explosion.

Make sure its range/dissipation distance is quite large, so your camera can "hear" the explosion from a long distance away.

To cause the shake, call one of this component's `GenerateImpulse()` methods, or `GenerateImpulseAt(position of explosion, Vector3.up)` if the component is attached to an object away from the actual explosion site.
> 0 votes

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


# Question
Title: Polling events with SDL results in stuttering response when dealing with multiple objects
I'm new to SDL programming and I'm not quite sure I got how it handles events. Given an instance like this defined in "game.c":

```
static struct {

  SDL_Window* window;
  SDL_Renderer* renderer;
  BinaryTree* objects;

} game = { NULL, NULL, NULL };

```

(Which of course gets properly initialized)

My game loop is defined in the same file as follows:

```
void game_run() {

  bool closeRequested = false;

  while(closeRequested == false) {

    SDL_RenderClear(game.renderer);

    binaryTree_startIteration(game.objects);

    while(binaryTree_hasNext(game.objects)) {

      GameObject* gameObject = (GameObject*) binaryTree_getNext(game.objects);

      SDL_Event event;

      while(SDL_PollEvent(&event)) {

        if(event.type == SDL_QUIT) {

          closeRequested = true;
        }
        else {

          if(event.type == SDL_KEYDOWN) {

            gameObject_onKeyPressed(gameObject);

            if(event.key.keysym.scancode == SDL_SCANCODE_UP) {

              gameObject_onUpKeyPressed(gameObject);
            }

            if(event.key.keysym.scancode == SDL_SCANCODE_DOWN) {

              gameObject_onDownKeyPressed(gameObject);
            }

            if(event.key.keysym.scancode == SDL_SCANCODE_LEFT) {

              gameObject_onLeftKeyPressed(gameObject);
            }

            if(event.key.keysym.scancode == SDL_SCANCODE_RIGHT) {

              gameObject_onRightKeyPressed(gameObject);
            }
          }

          if(event.type == SDL_KEYUP) {

            //
          }
        }
      }

      gameObject_onRendering(gameObject);
      SDL_RenderCopy(renderer, gameObject_getTexture(gameObject), NULL, gameObject_getDestination(gameObject));
    }

    SDL_RenderPresent(game.renderer);
  }
}

```

`game.objects` contains every object which has to be rendered (via `game.renderer`) onto the the window (`game.window`). So, on each frame `game.objects` gets iterated on and for each element various functions get executed, before its texture is loaded to the renderer.

Of course `gameObject_onRightKeyPressed()` is called only if the right key was pressed, so if this function is defined as

```
void gameObject_onRightKeyPressed(GameObject* gameObject) {

  gameObject->destination.x += 1,
}

```

On each frame that the right key is pressed, gameObject's texture will move by 1 pixel to the right.

This works perfectly if `game.objects` contains only one element, but if a second element gets added, only the first one will smoothly respond to my input, while the other will move by 1 or 2 pixels just once in a while by keeping the right key pressed. It's like the first element contained in `game.objects` "steals" the input, so that when the second element's turn comes, there's no input for it to respond to. What did I do wrong?

# Answer
Your game loop doesn't follow the traditional pattern of polling for input, updating your objects, and finally rendering them. Your current implementation will result in exactly what you describe, where the first object receives all of the input events SDL sends you. So instead of what you have currently, you want something like the following:

```
while (running)
{
    SDL_Event event;
    while (SDL_PollEvent(&event))
        ProcessEvent(event);

    UpdateAllObjects();

    ClearRenderer();
    RenderAllObjects();
    PresentRenderer();
}

```

The reason for this is that when you poll an event, SDL removes it from the event queue and considers it processed, this is why your first objects receives all the events.

As to how to implement the event handling, one option would be to invert the loop you currently have, so `ProcessEvent` could look something like the following:

```
void ProcessEvent(SDL_Event& event)
{
    if (event.type == SDL_KEYDOWN)
    {
        for (GameObject* object : objects)
            object->OnKeyDown(event.key.keysym);
    }
}

```

So instead of looping over objects first, and events second, we loop over events first, and distribute each event to all objects that listen to that event.

Alternatively you can maintain booleans of the current keyboard state, and check for those while updating the objects.
> 3 votes

---
Tags: sdl, c, events
---


# Question
Title: How can I get the name of a scriptable object via code
How can I get the name of a scriptable object, same way I would a game object `gameObject.name`?

I've tried:

```
object.name
scriptableObject.name
ScriptableObject.name
name
this.name

//String GetName()
WorldObjectData obj = ScriptableObject.CreateInstance<WorldObjectData>();
SerializedObject serializedObject = new SerializedObject(obj);
return serializedObject.FindProperty("m_name");

```

I can see that ScriptableObject extends Object, which has the .name attribute. But cant access it.

# Answer
> 2 votes
Presumably you started by trying the most obvious thing, `object.name`, the same way you would with a game object?

They both inherit from `UnityEngine.Object` which is where the `.name` field is defined.

---
Tags: unity
---


# Question
Title: 2D Platformer Multiple Body Collision Response
I've been stuck for the past few days on implementing multiple body collision response, and I can't seem to find any good resource to help me advance.

Colliding between two objects is simple enough. What I have so far is this:

```
    public static void ResolveCollision(ref Vector3 aVelocity, float aMass,
                                        ref Vector3 bVelocity, float bMass)
    {
        var totalMass = aMass + bMass;
        var temp = (aMass / totalMass * aVelocity) + (bMass / totalMass * bVelocity);
        bVelocity = (bMass / totalMass * bVelocity) + (aMass / totalMass * aVelocity);
        aVelocity = temp;
    }

```

This works fine in resolving collisions individually between objects. The issue that I need to resolve is when two or more bodies are involved in the calculation. For example, pushing an object against a wall or pushing two objects next to each other in the same direction. The component missing in my code is summing up the masses of the objects involved so that the final displacement is believable.

I am hesitant to implement a solution that once resolving the collision between A and B, that B will go and test its movement and resolve collisions between B and C, and return a response back to A to adjust itself to account for any findings, because that could become messy and recursive.

I have also considered an "island" approach, where connecting bodies form an "island" that has a total mass which would be used when resolving collisions. However, this does not solve for the case of pushing an object against a wall, as I would omit walls and floors from being part of islands as their infinite mass would affect calculations of pushing objects vertially or horizontally respectively, if they are contributing their mass to the island.

Are either of my suggestions close to the mark, or what kind of pattern could I use to efficiently resolve collisions between multiple bodies?

# Answer
I'm writing the answer for anyone interested, or who stumbles down the same path as me. Credit goes to DMGregory and Bennett Foddy.

The common solution present in many physics middlewares, is to just iterate the same list of collision pairs multiple times and only individually resolve collisions. The expected result is something that can be deemed as "good enough" in a performance critical environment.

Specifically to my question above, given objects sitting in a row: A -\> B -\> C, and applying a force to A

* A will resolve with B (and yes, only accounts for the mass of the two)
* B will resolve with C. B gets given a new velocity
* In a second iteration, A will resolve with B again which has a new velocity, pushing backwards on A

A pseudo-code example might look as follows:

```
while numIterations < desiredIterationCount
{
    foreach collisionPair in collisionList
    {
        resolve collision
        update position of each item in pair
    }
}

```
> 2 votes

---
Tags: physics, collision-resolution
---


# Question
Title: Error while trying to Build APK, fails when profile option is enabled
When I build normally my android app it execute without no problems, but when I go to File -\> Buil and Run and I eneble Development Build and Autoconnect to profiler I got this error

```
CommandInvokationFailure: Gradle build failed.
C:/Program Files/Unity/Hub/Editor/2019.1.14f1/Editor/Data/PlaybackEngines/AndroidPlayer/Tools/OpenJDK/Windows\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2018.4.4f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-5.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleDebug"

stderr[

   FAILURE: Build failed with an exception.

   * What went wrong:
   Execution failed for task ':checkDebugDuplicateClasses'.
   > 1 exception was raised by workers:
   java.lang.RuntimeException: Duplicate class bitter.jnibridge.JNIBridge found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class bitter.jnibridge.JNIBridge$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.Camera2Wrapper found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleARCoreApi found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrApi found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrProxy found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrProxy$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrProxy$2 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrProxy$3 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrProxy$4 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrProxy$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrVideo found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.GoogleVrVideo$GoogleVrVideoCallbacks found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.NativeLoader found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.ReflectionHelper found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.ReflectionHelper$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.ReflectionHelper$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$10 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$11 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$12 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$13 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$14 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$15 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$16 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$17 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$18 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$19 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$2 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$20 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$21 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$22 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$23 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$3 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$4 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$5 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$6 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$7 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$8 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$9 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$b found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$c found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$d found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$e found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$e$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$e$2 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayer$f found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityPlayerActivity found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityWebRequest found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityWebRequest$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.UnityWebRequest$2 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.a$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.a$2 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.a$3 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.a$4 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.a$5 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.a$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.b found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.b$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.b$b found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.c found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.c$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.d found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.e found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.f found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.g found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.h found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.i found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.j found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.k found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.k$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.k$2 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.k$3 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.l found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.l$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.l$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.m found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.n found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.o found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.o$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.p found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.p$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.p$b found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.q found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.q$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.q$1$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.q$1$1$1 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.q$2 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.q$3 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.q$4 found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class com.unity3d.player.q$a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class org.fmod.FMODAudioDevice found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)
   Duplicate class org.fmod.a found in modules classes-2.jar (:openix-release:) and unity-classes.jar (unity-classes.jar)

   Go to the documentation to learn how to <a href="d.android.com/r/tools/classpath-sync-errors">Fix dependency resolution errors</a>.

 * Try:
 Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

 * Get more help at https://help.gradle.org

 BUILD FAILED in 21s
 ]
 stdout[
      > Task :preBuild UP-TO-DATE
      > Task :preDebugBuild
      > Task :compileDebugAidl NO-SOURCE
      > Task :compileDebugRenderscript NO-SOURCE
      > Task :checkDebugManifest
      > Task :generateDebugBuildConfig
      > Task :prepareLintJar UP-TO-DATE
      > Task :generateDebugSources
      > Task :javaPreCompileDebug
      > Task :mainApkListPersistenceDebug
      > Task :generateDebugResValues
      > Task :generateDebugResources
      > Task :mergeDebugResources
      > Task :createDebugCompatibleScreenManifests
      > Task :processDebugManifest
      > Task :processDebugResources
      > Task :compileDebugJavaWithJavac
      > Task :compileDebugSources
      > Task :mergeDebugShaders
      > Task :compileDebugShaders
      > Task :generateDebugAssets
      > Task :mergeDebugAssets
      > Task :validateSigningDebug
      > Task :signingConfigWriterDebug
      > Task :checkDebugDuplicateClasses FAILED

      Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
      Use '--warning-mode all' to show the individual deprecation warnings.
      See https://docs.gradle.org/5.1.1/userguide/command_line_interface.html#sec:command_line_warnings 18 actionable tasks: 17 executed, 1 up-to-date
                ]
      exit code: 1
      UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <62f761e6ab1445a38cdcb4ac36512695>:0)
      UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <62f761e6ab1445a38cdcb4ac36512695>:0)
      vUnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <62f761e6ab1445a38cdcb4ac36512695>:0)
      UnityEditor.Android.AndroidJavaTools.RunJava (System.String args, System.String workingdir, System.Action`1[T] progress, System.String error) (at <62f761e6ab1445a38cdcb4ac36512695>:0)
      UnityEditor.Android.GradleWrapper.Run (Unit<message truncated>`

```

I'm using Unity 2018.4.4.f1 and in my project I have an \*.aar file that I made using Android Studio

I would appreciate any help you can give

# Answer
You are using a plugin, either a `.aar` or `.jar`, that is compiled with the `UnityPlayer.jar` (or `classes.jar`) file. Both `classes.jar` are compiled in your final build, so it throws a duplicate class exception.

To avoid this, try to add on your plugin module gradle, on the dependencies config, the following:

```
compileOnly files('./libs/classes.jar') // Avoid redundant Unity Player in final application APK

```

So your `.gradle` looks like:

```
//...
dependencies {
    //...

    compileOnly files('./libs/classes.jar') // Avoid redundant Unity Player in final application APK
    ///...
}
//...

```
> 1 votes

---
Tags: unity, java, android-studio, build-process, profiler
---


# Question
Title: Not able to find the constraints option in the Rigidbody component
I am working on a game tutorial right now and I need to freeze constraints for a model prefab. I add a `Rigidbody` component and I want to freeze rotations on the x and z axes. However, I am not able to find the option in the component. Is there another way to access rotation constraints (I do not want to code the constraints at the moment)? Or is there something I am missing in the new version. Please do let me know. Thanks

I am using Unity 5.6.7f1 Personal

# Answer
> 1 votes
Your inspector is in Debug mode.

Click the three-dot ⋮ icon in the top-right of the Inspector tab, next to the lock icon, and select "Normal"

The constraints section then appears as a fold-out near the bottom.

---
Tags: unity, rigidbody
---


# Question
Title: How to Iterate thru game object and access scripts by name?
I'm using a "toggle visibility" script on many objects in my scene, and in my `gameController` class I'm storing references to them in an array like this:

```
public Fields[] fields;

```

then I access them by the array index:

```
fields[0].setVisibility(true);

```

This works fine, but this list is growing and everything is getting unmaintainable.

So I would like to iterate thru the references to the objects, find the script by its game object name, and call the required function `setVisibility(state)`.

A call, if possible should look like this:

```
GameObjectName.ScriptName.FunctionCall.State

```

In this way, I would have a clear overview of my code.

Is this possible in Unity C#?

# Answer
### This sets GameObjects' visibility by name by activating/deactivating them:

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

public class Utility : MonoBehaviour
{
    static Dictionary<string, GameObject> gameObjects;

    public void Awake()
    {
        gameObjects = new Dictionary<string, GameObject>();
        foreach (var o in Resources.FindObjectsOfTypeAll<GameObject>())
            if (o.CompareTag("MyTag"))
                gameObjects.Add(o.name, o);
    }

    static public void SetVisible(string name, bool visibility = true)
    {
        gameObjects[name].SetActive(visibility);
    }
}

```

### This makes the game object named "AnitaBath" visible by activating it

```
Utility.SetVisible("AnitaBath");

```

### This makes the game object named "AnitaBath" invisible by deactivating it

```
Utility.SetVisible("AnitaBath", false);

```

### How to Use This Script

This script should be added to a unique object in your scene like *GameManager*. It enumerates all objects in the scene tagged "MyTag" whenever it's Awake() method is called.

It assumes GameObject names are unique, you've created a new tag called "MyTag" and added this tag to the objects you'll be calling `SetVisible` on.

If you don't use the tag, you run the risk of affecting hidden internal objects (e.g., "SceneLight", "InternalIdentityTransform", "PreviewMaterials", "Cone", "Cube", ...)
> 1 votes

# Answer
### This sets GameObjects' visibility by name by enabling/disabling their MeshRenderer:

```
static public class Utility
{
    static public void SetVisible(string name, bool visibility = true)
    {
        GameObject.Find(name).GetComponent<MeshRenderer>().enabled = visibility;
    }
}

```

### This makes the game object named "AnitaBath" visible by activating it

```
Utility.SetVisible("AnitaBath");

```

### This makes the game object named "AnitaBath" invisible by deactivating it

```
Utility.SetVisible("AnitaBath", false);

```

### Assumptions

This script assumes the GameObjects you are working with are *active* and contain a `MeshRenderer` component
> 2 votes

---
Tags: c#, scripting, gameobject
---


title: How do you make small icons look good?

text:
# Question
Title: How do you make small icons look good?
I am running into an issue with my UI.

Basically I need to have a lot of small icons, similar to many other games, here is an example:

With Mip maps:

As you can see, these look awful. This is simply a UI Image with size 15x15, it seems when they get too small it simply does not look good. It has nothing to do with import options or anti-aliasing, I have tried everything there. I submitted it as a bug but according to Unity it simply will not look good when images are scaled down too much.I have tried both PNG with large resolutions and small, I have exported the .SVG vector image and tried using that, all look bad when scaled down.

So what are my options then when I need small icons? How do other games do it?

Here is a link to the actual .png file: https://ibb.co/nDG0hmD

For reference, here are the same icons zoomed in, as you can see, they look fine:

Im developing for PC.

# Answer
> 1 votes
This is an attempt to use font-hinting to give you more control over how your graphics are rendered when scaled down.

### This is your UI with the icons implemented as a hinted font:

*StackExchange scales images down, so double click the images*

### Same image as above in the center, but with your samples flanking it (double click it):

### Same as above, but at 3X scale (*double click it*):

### 3X Animated GIF of icons translating downward by partial pixels (*double click it*):

### Text Object vs TextMeshPro (seriously, double click it)

Again, StackExchange rescales and resamples everything, so double click the images to see them un-mangled.

I imported the regular fonts with "Hinted Smooth":

I'm not an expert at creating hinted fonts or how best to render them in Unity. If anybody has tips for using hinting in Unity more effectively than I've done here, please share.

The animated GIF suggests to me that hinting isn't applied effectively when text can be positioned between pixels like I was doing.

### REF

# Answer
> 1 votes
There are two easy ways to fix this issue in the import settings for your icon texture, each which has its own pros and cons:

1. Enable Mip Maps. This tells Unity to generate multiple versions of the texture at different smaller resolutions. This way the image will generally look much less aliased at lower resolutions. However, at some screen resolutions the texture may appear slightly blurry (e.g. the optimal size would be 40x40 but the closest mipmap is 32x32 so Unity scales up the 32x32 mipmap slightly). It also increases your build size slightly since the build has to include multiple versions of each texture (IIRC the rule of thumb is that the texture will take up 33% more space when mipmaps are enabled). If your texture is in an atlas, you will need to enable mipmaps for the atlas.
2. Reduce the "max size", which is effectively the same as reducing the size of your texture in an image editor before importing it into Unity. This can work well when the resolution of the final game is known - e.g. if it's a console game that will always run at exactly 720p. However, if your game will be on a platform where screen resolution can vary widely (e.g. mobile, PC), the new smaller size might be *too small* for some resolutions, causing the icon to look blurry.

---
Tags: unity
---


# Question
Title: Difference between #DEBUG and #DEVELOPMENT_BUILD in Unity?
I've seen these two special compilation macros in our code base, What's the difference between `#Debug` and `#DEVELOPEMENT_BUILD` in Unity? What's the main purpose of using each?

```
#if DEBUG
Debug.Log("DEBUG");
#endif

#if DEVELOPMENT_BUILD
Debug.Log("DEVELOPMENT_BUILD");
#endif

```

# Answer
From these docs:

> You use the DEVELOPMENT\_BUILD #define to identify whether your script is running in a player which was built with the “Development Build” option enabled.

On the other hand, DEBUG doesn't exist.
> 4 votes

# Answer
In my testing with Unity 2018 (and it is different in Unity 2020 according to the comments), I found DEBUG is true in the editor and during development builds (it is true during the build so the code is compiled into the build). DEBUG is not true during release builds.

DEVELOPMENT\_BUILD is never true in the editor except during development builds (so the code is only runs in development builds, never in the editor). I'm not sure whether editor callbacks (surrounded with `#if DEVELOPMENT_BUILD`) would run while compiling a development build.

This preprocessor directive is not documented. I reported the omission as a documentation bug, but they may not consider it their responsibility to document .NET conventions.
> 1 votes

---
Tags: unity, c#, build-process, release
---


# Question
Title: Why won't my block Spaces/Holders hold my blocks when I drag onto them in Unity?
In my game I am trying to have numbered blocks and math operators be able to be dragged down into their respectively color coded holders (white holders = Numbers, black holders = operations). The spawn in color coded blocks called spawners. If you drop a block you were dragging in a space that isn't a holder, then the block would immediately snap back to its respective spawner.

However, I am now encountering this issue where 99% of the time when I drop the block onto its respective holder, the block snaps back to its spawner instead of staying there.

Here's the minimum reproducible code for dragging the blocks:

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

[RequireComponent(typeof(Collider2D))]
public class DragDrop : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
    [SerializeField] private SpriteRenderer _spriteRenderer;
    public SpriteRenderer _SpriteRenderer => this._spriteRenderer;
    [HideInInspector]public static bool isInSpace;
    [HideInInspector]public Vector3 initialPos;

    private void Start()
    {
        initialPos = transform.position;
        isInSpace = true;
    }

    public void OnDrag(PointerEventData eventData)
    {

        if (isInSpace == false)
        {
            Vector3 movement = new Vector3(
            x: (eventData.delta.x/3) * Time.deltaTime,
            y: (eventData.delta.y/3) * Time.deltaTime);

            this.transform.localPosition += movement;
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        isInSpace = false;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (isInSpace == false)
        {
            transform.position = initialPos;
        }
    }

#if UNITY_EDITOR
    private void Reset()
    {
        this._spriteRenderer = this.GetComponent<SpriteRenderer>();
    }
#endif
}

```

And Here's the code for receiving the blocks:

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

public class RecieveBlock : MonoBehaviour, IDropHandler
{
    public void OnDrop(PointerEventData Block)
    {
        if (Block.pointerDrag != null && Block.pointerDrag.tag == gameObject.tag)
        {
            Block.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
            DragDrop.isInSpace = true;
        }
    }

}

```

I have no idea why it doesn't set off the isInSpace bool to be true and stay there.

Heirarchy Image For Number Blocks:

Heirarchy Image For Operation Blocks:

Heirarchy Image For Holder Blocks:

Thank you for reading.

# Answer
> 0 votes
OnDrop takes the courser position. Changing the OnDrag event with this code (found in the docu), you will notice that as long as the mouse is over the destination, it is working. But not if the shapes are overlapping, the mouse is important.

```
public void OnDrag(PointerEventData eventData)
{
    if (isInSpace == false)
    {
        Ray ray = Camera.main.ScreenPointToRay(eventData.position);
        //Calculate the distance between the Camera and the GameObject, and go this distance along the ray
        Vector3 rayPoint = ray.GetPoint(Vector3.Distance(transform.position, Camera.main.transform.position));
        //Move the GameObject when you drag it
        transform.position = rayPoint;
    }
}

```

You could change it with a collision event that changes your bool isInSpace to true and snap it to the destination on OnEndDrag.

---
Tags: unity, mouse
---


# Question
Title: Texturing different block types on an optimized voxel mesh
I have a cubic world (like Minecraft) where I'm generating chunks. In those chunks, only visible vertices and faces are generated.

Currently, it means that if I have a 2x2x1 chunk, it will generate 8 triangles for the top part (2 for each block). I'm trying to generate only two following this greedy meshing method:

If I combine adjacent faces together, I'd still like to be able to draw transitions in materials between adjacent blocks, something like this:

As you can see it has 3 different tiles: grass, dirt-grass transition, and dirt.

Currently, my shader looks like this:

```
Shader "MultiTexture_Diffuse_Worldspace"
{

    Properties
    {
        _Color ("Main Color", Color) = (1,1,1,1)
        _TexAbove ("Above texture", 2D) = "surface" {}
        _TexSide ("Side texture", 2D) = "surface" {}
        _TexBelow ("Below texture", 2D) = "surface" {}
        _TexTopSide ("Top side texture", 2D) = "surface" {}
        _Scale ("Texture Scale", Float) = 1.0
    }

    SubShader
    {

        Tags
        {
            "RenderType"="Opaque"
        }

        CGPROGRAM
        #pragma surface surf Lambert

        struct Input
        {
            float3 worldNormal;
            float3 worldPos;
        };

        sampler2D _TexAbove;
        sampler2D _TexSide;
        sampler2D _TexBelow;
        sampler2D _TexTopSide;
        float4 _Color;
        float _Scale;

        void surf (Input IN, inout SurfaceOutput o)
        {
            float2 UV;
            fixed4 c;

            if(abs(IN.worldNormal.y > 0.5))
            {
                UV = IN.worldPos.xz;
                c = tex2D(_TexAbove, UV* _Scale);
            }
            else if(abs(IN.worldNormal.x) > 0.5)
            {
                UV = IN.worldPos.yz;
                c = tex2D(_TexSide, UV* _Scale);
            }
            else if(abs(IN.worldNormal.z) > 0.5)
            {
                UV = IN.worldPos.xy;
                c = tex2D(_TexSide, UV* _Scale);
            }
            else
            {
                UV = IN.worldPos.xz;
                c = tex2D(_TexBelow, UV* _Scale);
            }

            o.Albedo = c.rgb * _Color;
        }
        ENDCG
    }
}

```

How would I modify this shader to work with faces that have been merged together? Or would I have to keep separate faces per block and handle them individually?

# Answer
> 6 votes
Quoting the meshing page you link:

> It isn’t too difficult to modify the code deal with either multiple block types or different normal directions. What you would do is modify the array called “mask” in the code to store an integer value which encodes the type of each block. You’d need at least 1 bit for orientation, and then you could use the rest to store block color or whatever. Then when you build the greedy quad, you store the type of the block you are scanning over and only group blocks which are the same type together.

The author elaborates in part 2:

> The general idea is pretty simple. What you do is group blocks together according to their type, and then do the meshing on each part separately:
>
> That’s it! This same idea works for normals too. All you need to do is add an extra bit to keep track of the orientation. To show that this isn’t so difficult, I made an updated demo that shows how some of these methods work for different voxel types.

That would give you something like this:

Here we've combined...

* the 4 grass faces on the top into a single combined grass face,
* the 8 grass-dirt faces into four (one on each side of the chunk),
* and the 12 all-dirt faces into 5 (one on the bottom and one on each side).

You could make each of these into a sub-mesh with its own material to be drawn in its own draw call with your current shader.

Or, you could combine all your block textures into an atlas texture to draw the whole multi-block-type chunk in a single draw call. You'd split the vertices shared by multiple different block types, and give each copy a distinct texture coordinate - say, the top-left corner of the texture to use in your atlas, or its index in the stack if using an array texture. If you're using a flat 2D atlas, you'd need to modify your shader to do the texture wrapping in the shader math, since the sampling hardware won't do it for you.

# Answer
> 7 votes
Nice idea by the author.

From experience... High vertex counts aren't that much of a problem (100Ks, millions even). Dealing with complex UV mapping is far more so. Sometimes it is worth staying closer to the actual description of the surface (i.e. the backing 3D array), than optimising yourself into a place where it's not as easy to change the mesh when you need to do so (assuming you don't just rebuild the entire chunk each time a voxel changes). That is, it can help to have the ability to easily reference between mesh locations, and the data that formed it.

Assuming you intend to use textures: Remember that in any space where you have non-homogenous voxels but a single rectangular space, you will need to create a new texture specifically to map onto that plane... and every other heterogenous plane. Texture write / reads are not the fastest thing in the GPU pipeline. Worth it? Only you will know. For frequently-changed terrain, I'd avoid this.

(If using textures) I would stick with a simpler approach each cube face is its own set of non-shared vertices, with the ability to UV map a single cube-face texture at a time. If using vertex colours? - the world is your oyster.

---
Tags: unity, c#, shaders, 3d-meshes, voxels
---


# Question
Title: How to calculate a child UI image's anchoredPosition(?) based on screen position input?
How to calculate a child UI image's anchoredPosition(?) based on screen position input?

I'm trying to have the child UI image (Spotlight) show up where the eyeball UI is, but it seems to always be offset. The eyeball correctly shows up based on the Screen Position.

It is perfect when the Canvas is at 1080x1920 (set to scale)

But when I try it using others screen resolutions such as 1125x2436, the issue above shows up.

None of these attempts work. The gif is based on the one not commented out here:

```
p=Input.mousePosition; // screenPosition

    public static void SetRTPos(Transform g,Vector2 p,Canvas c)
    {
        RectTransform rt = g.GetComponent<RectTransform>();
        rt.anchorMin = Vector2.zero;rt.anchorMax = Vector2.zero;
        rt.pivot = Vector2.zero;
        // rt.anchoredPosition = RectTransformUtility.PixelAdjustPoint(p,g.parent,c);
        //rt.anchoredPosition = new Vector2(p.x* (float)c.pixelRect.x, p.y*(float)c.pixelRect.y);//  c.scaleFactor;
        rt.anchoredPosition = new Vector2(p.x*1080f/Screen.width,p.y*1920f/Screen.height );
        //rt.localPosition = RectTransformUtility.ScreenPointToLocalPointInRectangle(rt.parent.GetComponent<RectTransform>(),p,Camera.main,out p2)
   }

```

The UI RectTransform for `rt.parent`:

The UI RectTransform for `g` (not the x,y,z are updated at runtime):

# Answer
You had the right answer, you just used it wrong. `ScreenPointToLocalPointInRectangle` returns a boolean true/false, indicating *whether* the point is in the rectangle. To get its position inside that rectangle, you need to read the `out` parameter.

```
public static void SetRTPos(/*ask for the type you want*/ RectTransform rt, Vector2 p, Canvas c)
{
    var center = new Vector2(0.5f, 0.5f);
    rt.anchorMin = center;
    rt.anchorMax = center;
    rt.pivot = center;

    RectTransformUtility.ScreenPointToLocalPointInRectangle(
        (RectTransform)rt.parent, // No GetComponent needed, just cast it.
        p,
        Camera.main,              // Use null if canvas is Screenspace Overlay.
        out Vector2 localPoint    // The position is given as an out parameter.
    );

    rt.anchoredPosition = localPoint;
}

```
> 0 votes

---
Tags: unity, unity-ui
---


# Question
Title: Godot - Quaternion slerp is altering initial rotation of an object
I have a player that shoots a rocket. If the rocket has a target, I use a quaternion slerp to make it home in on that target. Free firing the rocket goes directly forwards as expected. Setting a `tracking_speed` of 1 homes directly towards the target as expected. But for some reason if I set `tracking_speed` to less than 1, the rocket's initial direction becomes (0 0, 1) no matter where the ship is pointing and then proceeds to rotate towards the target. Code below.

```
var transformed_rotation:Transform = global_transform.looking_at(target.global_transform.origin, Vector3.UP)
var new_rotation:Quat = Quat(global_transform.basis).slerp(transformed_rotation.basis, tracking_speed)

set_global_transform(Transform(new_rotation, global_transform.origin))

```

# Answer
> 2 votes
The issue was that in `Quat(global_transform.basis)` the basis was not normalized first.

---
Tags: rotation, quaternion, godot, lerp
---


title: Blendshapes in Unity vs Blender

text:
# Question
Title: Blendshapes in Unity vs Blender
I have a model from a package that has existing Blendshapes that work fine. I'm a bit of a Blender newb, though. I'm trying to add a Blendshape for spikiness to a cube model. It's early WIP, but it looks roughly the way I expect it to in Blender. However, when exported and imported into Unity, the mesh with the blendshape applied isn't quite right - the spikes are sort of... plump, as if it isn't quite changing the vertices the same way. Is there anything specific that needs to be done with this process? Am I missing something, or is there some tuning I need to do in Blender prior to exporting the FBX?

Blender: http://www.labyrintheer.com/wp-content/uploads/2020/08/spike\_bs\_blender.mp4

Unity: http://www.labyrintheer.com/wp-content/uploads/2020/08/spike\_bs\_unity.mp4

# Answer
Alright, I was able to answer my own issue. The root cause had to do with Blender using quads as opposed to tris. The way I morphed the mesh for the blendshape did not allow for very good quad-\>tri conversion. I modified the way I managed the blendshape (moved all 8 surrounding vertices in toward the pulled vertex), and the spikes now look... like spikes.

If anyone comes to this because they have a similar issue - consider how your quads are going to convert to tris. If a single quad in Blender is stretched AND curved (it can happen in modeling) it will not become good tris as a single quad is *always* broken into exactly two tris.

In the following example, the face we're looking at, my initial attempt was like the right spike, and the resolved attempt was the left spike.

As you can see, the right spike creates two "shapes" of quads at the deformation. The larger quads (two on top, two on the bottom, two on each side) aren't really a huge issue, however the quads that make up each "quadrant" of the spike are problematic geometry. This image highlights their somewhat boomerang shape:

Given that there's no edge where the spike juts out, it's plausible that the FBX could be imported and have good tris that split there, but that's sort of a wish and a prayer.

Pulling in all eight surrounding vertices changes the breakdown of the geometry considerably. Here's another close-up:

Your mileage may vary, but as a game developer, I tend to think in tris and didn't really consider just how differently quads work, especially when they're parsed into tris at import.
> 2 votes

---
Tags: unity, blender, mesh, fbx
---


# Question
Title: setTransform() Box2D physics not working
It's my first time posting here!

I'm working on a top-down shooter game in LibGDX and Box2D (so gravity is set to `(0, 0)`). At the moment, to move my character, I'm using the setTransform() method. I understand it can be a bit buggy, but in past experiences the method worked fine and collisions were detected and handled.

Here's an image of my character (DynamicBody) colliding with a static obstacle. Even using `setTransform()`, it should try to push the character outside of the box's bounds? Bodies do not seem to be colliding.

Here's my `Player` code. The Vector2 set as `linearVelocity` is not being used.

```
public class Player extends BodyHolder implements Disposable {

    private float speed = 2.3f;

    private Sprite sprite;
    private Vector3 position;
    private Vector2 linearVelocity;
    private Vector3 mousePos;

    private static final Vector2 SIZE = new Vector2(93, 84);

    private int playerPhase = 0, prevPlayerPhase = 0;

    private int ID;
    private boolean isMain = false;

    public Player(final Vector2 position, final WorldManager world) {
        super(world, position, new Vector2(SIZE.x / 2, SIZE.y / 2), BodyDef.BodyType.DynamicBody, 0.8f, false, -1);
    }

    public Player(int id, Vector2 pos, WorldManager world, boolean main) {
        super(world, pos, new Vector2(SIZE.x / 2, SIZE.y / 2), BodyDef.BodyType.DynamicBody, 0.8f, false, id);

        this.ID = id;
        this.position = new Vector3(pos.x, pos.y, 0);
        this.mousePos = new Vector3();
        this.isMain = main;

        linearVelocity = new Vector2();

        getBody().setFixedRotation(true);

        sprite = new Sprite(new Texture(Gdx.files.internal("player/player_nogun.png")));
        playerPhase = 1;
    }

    public void update(SpriteBatch batch, ModifiedShapeRenderer renderer, CameraController cam) {

        sprite.setCenter(position.x, position.y);
        getBody().setTransform(position.x, position.y, 0);
//        getBody().setLinearVelocity(linearVelocity);
        if(isMain()) this.handleInput(cam);

        if(prevPlayerPhase != playerPhase) {
            prevPlayerPhase = playerPhase;
            if(playerPhase == 1) {
                sprite = new Sprite(new Texture(Gdx.files.internal("player/player_nogun.png")));
                sprite.setOrigin(sprite.getOriginX() + 5, sprite.getOriginY());
            } else if(playerPhase == 2) {
                sprite = new Sprite(new Texture(Gdx.files.internal("player/player.png")));
            }
        }

        for(Gun gun : GunSpawner.getGuns()) {
            if(gun.obtainObject().getBoundingRectangle().overlaps(this.sprite.getBoundingRectangle())) {
                gun.hoverOver(this);
            }
        }

        batch.setProjectionMatrix(cam.getCamera().combined);
        batch.begin();
        sprite.draw(batch);
        batch.end();
    }

    public void handleInput(CameraController cam) {
        mousePos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        cam.getCamera().unproject(mousePos);
        sprite.setRotation((float) (MathUtils.radiansToDegrees * Math.atan2((position.y - mousePos.y) , (position.x - mousePos.x))));

        boolean keyPressed = false;

        if(Gdx.input.isKeyPressed(Input.Keys.W)) {
            position.y += speed;
            linearVelocity.y = 100;
            keyPressed = true;
        }
        if(Gdx.input.isKeyPressed(Input.Keys.S)) {
            position.y -= speed;
            linearVelocity.y = -100;
            keyPressed = true;
        }
        if(Gdx.input.isKeyPressed(Input.Keys.A)) {
            position.x -= speed;
            linearVelocity.x = -100;
            keyPressed = true;
        }
        if(Gdx.input.isKeyPressed(Input.Keys.D)) {
            position.x += speed;
            linearVelocity.x = 100;
            keyPressed = true;
        }

        if(keyPressed) {
            keyPressed = false;
        } else {
            linearVelocity.set(0, 0);
        }

        if (Gdx.input.isKeyJustPressed(Input.Keys.K)) {
            Gdx.app.log(position.x + "", position.y + "");
        }

    }

    public Vector2 get2DPosition() {
        return new Vector2(position.x, position.y);
    }

    public int getID() {
        return ID;
    }

    public boolean isMain() {
        return this.isMain;
    }

    public Sprite obtainObject() {
        return sprite;
    }

    @Override
    public void dispose() {

    }
}

```

If it's any help, I'm stepping the world at 6 velocity iterations and 2 position iterations.

# Answer
> 1 votes
Setting the transform directly can lead to weird results (as you point out yourself), and it's often better to control your bodies using impulses, even if it is sometimes difficult to tune it to perfection to get just the sort of movement you're looking for.

Depending on the kind of movement you're looking for I'd recommend using `applyLinearImpulse` to move your avatar and `setAngularVelocity` to rotate it.

Using these two it's easy to get something like this up and running:

The full source code for that is:

```
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.RandomXS128;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;

public class Box2DKeyBoardControlledGame extends Game {

    private OrthographicCamera camera;
    private World world;
    private Box2DDebugRenderer renderer;
    private RandomXS128 rnd = new RandomXS128();

    private Body player;
    private Array<Body> obstacles = new Array<>();

    private final ObjectMap<Integer, Boolean> keyboardState = new ObjectMap<>();

    @Override
    public void create() {
        float aspectRatio = (float) Gdx.graphics.getHeight() / (float) Gdx.graphics.getWidth();

        camera = new OrthographicCamera(100.0f, 100.0f * aspectRatio);

        renderer = new Box2DDebugRenderer();
        world = new World(new Vector2(0.0f, 0.0f), false);

        player = createPlayer();
        for (int i = 0; i < 16; ++i) {
            obstacles.add(createObstacle(rnd.nextInt(100) - 50.0f, rnd.nextInt(100) - 50.0f));
        }

        Gdx.input.setInputProcessor(new InputAdapter() {
            @Override
            public boolean keyDown(int keycode) {
                keyboardState.put(keycode, true);
                return true;
            }

            public boolean keyUp(int keycode) {
                keyboardState.put(keycode, false);
                return true;
            }
        });
    }

    private Body createPlayer() {
        CircleShape shape = new CircleShape();
        shape.setRadius(1.0f);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.linearDamping = 8.0f; // You might want to tweak this to get the player to slow down at a different rate

        Body body = world.createBody(bodyDef);
        body.createFixture(fixtureDef);

        return body;
    }

    private Body createObstacle(float x, float y) {
        PolygonShape shape = new PolygonShape();
        shape.setAsBox(1.0f + rnd.nextFloat() * 2.0f, 1.0f + rnd.nextFloat() * 2.0f);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.StaticBody;

        Body body = world.createBody(bodyDef);
        body.createFixture(fixtureDef);
        body.setTransform(x, y, rnd.nextFloat() * MathUtils.PI2);

        return body;
    }

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

        final float accelerationFactor = 64.0f;
        final float turnFactor = 256.0f;

        Vector2 direction = (new Vector2(1.0f, 0.0f)).rotate(player.getAngle() * MathUtils.radiansToDegrees);
        Vector2 impulse = new Vector2();
        float turn = 0.0f;

        if (keyboardState.get(Input.Keys.UP, false))
            impulse.set(direction).scl(accelerationFactor);
        if (keyboardState.get(Input.Keys.DOWN, false))
            impulse.set(direction).scl(-accelerationFactor);
        if (keyboardState.get(Input.Keys.LEFT, false))
            turn = turnFactor;
        if (keyboardState.get(Input.Keys.RIGHT, false))
            turn = -turnFactor;

        player.setFixedRotation(false);
        player.applyLinearImpulse(impulse.scl(Gdx.graphics.getDeltaTime()), Vector2.Zero, true);
        player.setAngularVelocity(turn * Gdx.graphics.getDeltaTime());

        camera.update();
        world.step(Gdx.graphics.getDeltaTime(), 6, 2);

        renderer.render(world, camera.combined);
    }
}

```

The difficult part is to tune and tweak the parameters of your `FixtureDef`s, `BodyDef`s and impulses to get exactly the movement you're looking for.

---
Tags: libgdx, box2d, shooter
---


# Question
Title: What is the proper strategy to manage vertex buffers?
I have created a large variety of shaders for my game engine for different use cases. The vertex input for the shaders depend on what I want to do with them. For example, if I want to just render the wireframe of a mesh, I do not need texture coordinates, normals, etc. because I just need basic vertex information. However, when I render animated meshes (I use Skinned Animation), then I need additional information like joint link weights for each vertex.

My question is: **What is the best way to manage Vertex Buffers?** Do I create a Vertex Buffers for each use case when I create the model and store them for later use, i.e. I select at run-time which of the stored Vertex Buffers to use for rendering? Do I create the Vertex Buffer I need at run-time in each render cycle? What is the best way to do it?

I am using DirectX 11 and C# (using SharpDX as wrapper).

# Answer
> 2 votes
If there was just one "proper strategy" or "best way", the API would give you only that one option to ensure everyone got the best outcome.

But that's not how gamedev works. Different games have different needs.

* In one game, every mesh needs texture coordinates and normals and tangents, so they can set up every buffer following that pattern, consistently, and never change it.
* In another game, meshes sometimes need to be drawn without normals/tangents, but only rarely/unpredictably (say, when the player toggles to X-Ray vision), so it makes sense to keep using the full buffer all the time even if it contains some unneeded info for some passes.
* In another game, all the environment meshes need normals and tangents, character meshes need all that plus skinning information, but the UI meshes need only texture coordinates, and all these sets are disjoint. So the developers can simply tag each mesh asset with the appropriate vertex buffer contents it needs as part of their asset metadata, and build the buffer once on load, never changing it after that.
* In another game, the same mesh is viewed with wildly different shaders in different game states, and it's performance-critical that it not have any excess information in its vertex buffer, so the game re-generates its buffer each time it transitions to a new state to have just the info needed in that state.
* ...etc.

We don't know which of these games you're making. You might not even know that yet!

But it's probably a safe bet that your models typically need texture coordinates and normals, so build a basic buffer that contains what you need for most of the cases you've come across thus far.

Then, when you find a case that needs more information, change your code to suit that case. (Maybe you tag the asset as needing a different buffer structure on import, maybe you re-generate the buffer when you enter the specific state that needs the extra info)

When you find a case that needs *less* information, profile. Maybe it's not a problem to be sending the extra data down the pipe, and you can focus on something else for now, until it becomes a problem.

---
Tags: directx, directx11, sharpdx, vertex-buffer, vertex-shader
---


# Question
Title: How to create a projectile path in unity using physics
I want to create a jump function that launches a RigidBody2D along a low, long, trajectory. In the following examples, I have set the linear and angular drag to 0, to eliminate any possibility of unwanted friction calculations. Mass is set to 1, and gravity to 3 for the rigidbody. At present, I have tried variations on this:

```
rb.AddForce(new Vector2(x,y));

```

or:

```
rb.velocity = new Vector2(x, y);

```

These have been implemented in my CharacterController script, in a public void LongJump() function.

As I understand it, AddForce respects physics, while velocity simply sets velocity to a given value, irrespective of physics. Thus, when using AddForce(new Vector2(x,y)), I expect the magnitude of the force to be sqrt(x^2 + y^2) and the direction to be sin(arctan(y/x)), or thereabouts. Given this, I would expect normal, kinematic equations to describe the result (i.e., x(t) = x0 + xt - .5gt^2).

However, instead of this, the rigidbody simply flies in the direction of motion at roughly the correct angle, rises slightly at the end of the frame, and then falls directly downward without preserving the x-direction velocity.

I would like to know how to get correct physics behavior. I can only guess there's something I don't know about unity's handling of physics.

I have found some tutorials online, for creating parabolic motion, but all of them require a known target, which is not helpful. My function is meant to allow the jump from any point to any other point, and I need to respect collisions.

**Edit. Here is the Character Controller. It is based on brackley's (from his tutorial series on 2d games). The longjump() as written is just one variation of things I've tried, so think of it as a placeholder:**

```
using UnityEngine;
using UnityEngine.Events;

public class CharacterController2D : MonoBehaviour
{

    [SerializeField] private float m_JumpForce = 400f;                          // Amount of force added when the player jumps.
    [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f;          // Amount of maxSpeed applied to crouching movement. 1 = 100%
    [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;  // How much to smooth out the movement
    [SerializeField] private bool m_AirControl = false;                         // Whether or not a player can steer while jumping;
    [SerializeField] private LayerMask m_WhatIsGround;                          // A mask determining what is ground to the character
    [SerializeField] private Transform m_GroundCheck;                           // A position marking where to check if the player is grounded.
    [SerializeField] private Transform m_CeilingCheck;                          // A position marking where to check for ceilings
    [SerializeField] private Collider2D m_CrouchDisableCollider;                // A collider that will be disabled when crouching

    const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
    private bool m_Grounded;            // Whether or not the player is grounded.
    const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
    private Rigidbody2D m_Rigidbody2D;
    private bool m_FacingRight = true;  // For determining which way the player is currently facing.
    private Vector3 m_Velocity = Vector3.zero;

    //The values below are my additions to this code.
    [SerializeField] private Transform m_SideCheck;//position to check if player is wall sliding (right)
    const float k_SideCheckRadius = .5f; //Radius for determining if a wall jump is possible.
    private bool m_WallSliding;//boolean to check if side jump is allowed.
    private bool m_WallSlideValidation;//Bool to ensure we can jump only once.

    [Header("Events")]
    [Space]

    public UnityEvent OnLandEvent;

    [System.Serializable]
    public class BoolEvent : UnityEvent<bool> { }

    public BoolEvent OnCrouchEvent;
    private bool m_wasCrouching = false;

    public BoolEvent onWallSlideEvent;//An event to check when wallsliding may be happening.

    private void Awake()
    {
        m_Rigidbody2D = GetComponent<Rigidbody2D>();

        if (OnLandEvent == null)
            OnLandEvent = new UnityEvent();

        if (OnCrouchEvent == null)
            OnCrouchEvent = new BoolEvent();

        if (onWallSlideEvent == null)
            onWallSlideEvent = new BoolEvent();
    }

    private void FixedUpdate()
    {
        bool wasGrounded = m_Grounded;
        m_Grounded = false;

        // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
        // This can be done using layers instead but Sample Assets will not overwrite your project settings.
        Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].gameObject != gameObject)
            {
                m_Grounded = true;
                if (!wasGrounded)
                    OnLandEvent.Invoke();
            }
        }

        //this section addresses the wall slide conditions.
        bool wasWallSliding = m_WallSliding;
        m_WallSliding = false;//Assumes we are not wall sliding.
        if (m_Grounded == true)
        {
            m_WallSlideValidation = true;//Used to ensure we can only wall jump once.
        }
        Collider2D[] walls = Physics2D.OverlapCircleAll(m_SideCheck.position, k_SideCheckRadius, m_WhatIsGround);//Walls
        for (int i = 0; i < walls.Length; i++)
        {
            if ((walls[i].gameObject != gameObject) && (m_Grounded != true))//Second condition ensures we are not grounded. We only want to wall jump when not grounded.
            {
                m_WallSliding = true;
                //if (!wasWallSliding)//This part needs to be fixed, so that the animation is properly invoked.
                //  onWallSlideEvent.Invoke(true);//this line would invoke the wallslide animation, if there were one.
            }
        }
    }

    public void Move(float move, bool crouch, bool jump)
    {
        // If crouching, check to see if the character can stand up
        if (!crouch)
        {
            // If the character has a ceiling preventing them from standing up, keep them crouching
            if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
            {
                crouch = true;
            }
        }

        if (!Physics2D.OverlapCircle(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround))//note the "!"
        {
            //This fixes the issue with crouch movement speed remaining constant even if you crouch walk off a ledge.
            crouch = false;
        }

        //only control the player if grounded or airControl is turned on
        if (m_Grounded || m_AirControl)
        {
            // If crouching
            if (crouch)
            {
                if (!m_wasCrouching)
                {
                    m_wasCrouching = true;
                    OnCrouchEvent.Invoke(true);
                }
                // Reduce the speed by the crouchSpeed multiplier
                move *= m_CrouchSpeed;

                // Disable one of the colliders when crouching
                if (m_CrouchDisableCollider != null)
                    m_CrouchDisableCollider.enabled = false;
            } else
            {
                // Enable the collider when not crouching
                if (m_CrouchDisableCollider != null)
                    m_CrouchDisableCollider.enabled = true;

                if (m_wasCrouching)
                {
                    m_wasCrouching = false;
                    OnCrouchEvent.Invoke(false);
                }
            }

            // Move the character by finding the target velocity and smoothing the movement.
            Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);//This sets the x and y directions, but not the z direction.
            m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);//ref m_Velocity = zero.

            // If the input is moving the player right and the player is facing left...
            if (move > 0 && !m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
            // Otherwise if the input is moving the player left and the player is facing right...
            else if (move < 0 && m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
        }

        // If the player should jump...
        if (m_Grounded && jump)
        {
            // Add a vertical force to the player.
            m_Grounded = false;
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
        }

        //The portion below is my addition to this code.
        //Implements wall jump
        if (m_WallSliding && jump && m_WallSlideValidation)
        {
            // Add diagonal force to the player.
            WallJump();
            m_WallSliding = false;//ensures we make sure we're still wall sliding if we try this again.
            m_WallSlideValidation = false;//makes it so you can only walljump once.
        }

    }

    private void WallJump()
    {
        //My function to handle wall-jumping.
        float newForceY = .75f * m_JumpForce;
        float newForceX = -1f * m_JumpForce * transform.localScale.x;
        //Debug.Log(transform.localScale.x);
        m_Rigidbody2D.velocity = Vector3.zero;
        m_Rigidbody2D.AddForce(new Vector2(newForceX, newForceY));
    }

    //LongJump() should be made private and called by Move(), and the conditions of calling it should be shifted.
    public void LongJump()
    {
        //Trying this code. While loop did not work.
        m_Rigidbody2D.AddForce(new Vector2(0, m_JumpForce / 2));
        m_Rigidbody2D.velocity = new Vector2(100f, 0);
    }

    private void Flip()
    {
        // Switch the way the player is labelled as facing.
        m_FacingRight = !m_FacingRight;

        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
        //Debug.Log(theScale.x);
    }

    private void OnDrawGizmosSelected()
    {
        //This is for the editor. It simply draws a wire sphere around the transform of a given radius.
        //Basically excellent for debugging.
        Gizmos.DrawWireSphere(m_SideCheck.position, k_SideCheckRadius);
        Gizmos.DrawWireSphere(m_GroundCheck.position, k_GroundedRadius);
    }
}

```

# Answer
> 1 votes
Thanks to DMGregory, the issue was the m\_AirControl variable, which caused the velocity to rapidly fall when attempting to do a LongJump().

The full solution is this:

```
public void LongJump()
    {
        //This is fine
        m_AirControl = false;
        m_Rigidbody2D.AddForce(new Vector2(0, m_JumpForce / 2));
        m_Rigidbody2D.velocity = new Vector2(100f, 0);
    }

```

And then modify the move() function:

```
public void Move(float move, bool crouch, bool jump)
    {
        //Debug.Log("Move is :" + move);
        if (move != 0 || crouch == true || jump == true)
        {
            m_AirControl = true;
        }
    //[....]
    }

```

This will effectively disable air control for the duration of the jump, forcing the jump to follow the set trajectory based on the force inputs. Then the adjustments to move ensure that, when the player is next able to input a valid input, air control turns back on, allowing for control over the jump.

---
Tags: unity, c#, movement, projectile-physics
---


# Question
Title: What is the workflow of modeling 3D rooms?
I'm always struggling with creating flexible, reusable rooms for my underground-set games. When creating reusable rooms I have encountered the following problems:

* Size - levels can have wildly different sizes and separate objects for all of the sizes seems repetitive and unnecessary
* Holes in the room - i.e. windows, doors. There may be rooms with exactly the same size but different placement of doors, windows, etc... that only multiplies the amount of possible combinations

Possible solutions:

* Not creating whole rooms but creating separate walls, floors, roofs so I can mix and match in the engine later?
    + Those parts would still require different sizes, unless I am to put 1 object per square meter or similar
* Creating flexible Blender model so I can quickly change it export different variations of the room?

Thanks for any ideas, opinions, experiences

# Answer
> 1 votes
It sounds like you understand the pitfalls, so here is what I suggest in regards to room modeling.

Kits. Your best bet is to create kits that you can bash together in your engine of choice. For example, create a blank 1.5m by 1.5m wall. Then a wall of the same size, but with a window. Then another wall with a different style of window. Repeat these steps for their ceiling and floor, if you need variations on those as well. Then once you import into an engine, you just place the "piece" of wall required for that room. You could go a step further and create entire rooms, each with slightly different variations (window position, door size, etc) and export those entire rooms into the engine. This is more helpful if you are trying to build entire buildings more quickly, otherwise creating separate kits of walls and other surfaces will be easier.

Just to note, you can have different sized walls (full wall, half walls, etc) as long as they "snap" to the same grid. You don't want a wall that's 87cm tall and another that is 92cm. Try to keep it in multiples of two or ten.

This kit rule can be followed for different styles of doors and windows too. Just make sure they have an appropriate pivot point and are scaled correctly. (Make sure all kit items are centered to the world before you export, or else you will have pivot points that are WAY too far from the object and it will make placing them in the engine a nightmare)

---
Tags: blender, assets, workflow
---


# Question
Title: How to make it so the game waits on player input for a dialog system in Godot?
So i have most system set up im just at loss on make it so that the player has to click through the dialog. Currently all the dialog is stored in text files that are read into dictionary's like so.

```
var dic = {}

func test():
    var index = 1
    popup_centered(Vector2(0,2000))
    var line = dic[str(index)]
    $Text.set_text(line)

#loads file into dictionary
func load_file(filepath):
    dic = {}
    var file = File.new()
    file.open(filepath, 1)
    var index = 1
    while not file.eof_reached():
        var line = file.get_line()
        print("the line:")
        print(line)
        dic[str(index)] = line
    index += 1
    file.close()
    print(dic)
    test()

```

Where the test function is like i said above i want the code to wait for the players input and print the next line in the dictionary and then close when the dictionary is empty. Being new to Godot i dont know if there is a simple way to do this. Any help is appreciated and thank you in advance.

Also aside, i know there are a lot of plug-ins for Godot that can handle dialog if i download them, but i want to build this myself so i can learn, so please don't just say use a plug in.

# Answer
> 1 votes
Figured out a solution, Godot has built in functions that catch inputs that you can use. In this case its \_input(). Example as follows;

```
func _input(event):
if event.is_action_released("left_mouse") and active:
    print("left mouse clicked yay!")
    index += 1
    test()

```

It pays to read the documentation.

---
Tags: godot
---


title: Polygon draw order issue

text:
# Question
Title: Polygon draw order issue
I'm working on a software and I'd to move the rendering API from SlimDX to SharpDX. I've done that but I noticed that the solid polygon are not drawn correctly i.e., even if the polygon is at the back side of another polygon, part of it is visible, also part of the polygon lie inside terrain that is also visible. Below are the images from SlimDX implementation and SharpDX implementation for reference:

I tried to set the Stencil & ZBuffer but there are not working as expected. I've already applied DepthBias to it which worked fine with SlimDX but not with SharpDX.

Please let me know if, I'm missing something or I'm doing something wrong.

Update 1 (Polygon rendering):

```
// set the render state to device
device.SetRenderState(RenderState.AlphaTestEnable,
                      true);
device.SetRenderState(RenderState.AlphaBlendEnable,
                      true);
device.SetRenderState(RenderState.SourceBlend,
                      Blend.SourceAlpha);
device.SetRenderState(RenderState.SeparateAlphaBlendEnable,
                      true);
device.SetRenderState(RenderState.DestinationBlendAlpha,
                      Blend.One);
device.SetRenderState(RenderState.SourceBlendAlpha,
                      Blend.InverseDestinationAlpha);

// set the render state to the device
device.SetRenderState(RenderState.DepthBias,
                      -1E-06f);

this.effectVectoring.Begin(FX.None);

// binds the vertex buffer to device data stream
device.SetStreamSource(0,
                       this.vertexBuffer,
                       dataGeometry.FillVertexOffset,
                       stride);
// pass 1 to shader as a pass if it is 3D mode else 0
this.effectVectoring.BeginPass(is3D ? 1 : 0);
// renders the non-index geometric primitives using the data from current input stream
device.DrawPrimitives(SharpDX.Direct3D9.PrimitiveType.TriangleList,
                      0,
                      primitiveCount);
// end the pass
this.effectVectoring.EndPass();

this.effectVectoring.End();
device.SetRenderState(RenderState.AlphaBlendEnable,
                    false);
device.SetRenderState(RenderState.AlphaTestEnable,
                    false);
device.SetRenderState(RenderState.DepthBias,
                    0);
device.SetRenderState(RenderState.FillMode,
                    FillMode.Solid);
device.SetRenderState(RenderState.SeparateAlphaBlendEnable,
                    false);

```

Update 2 (Terrain rendering):

```
device.SetRenderState(RenderState.AlphaBlendEnable,
                      false);
device.SetRenderState(RenderState.AlphaTestEnable,
                      false);
device.SetRenderState(RenderState.CullMode,
                      Cull.Counterclockwise);

device.Indices = this.terrainIB;
device.SetStreamSource(0,
                       this.terrainVB,
                       0,
                       12);
device.VertexFormat = VertexFormat.Position;

// Set texture in effect...

effect.Begin(FX.None);

effect.BeginPass(pass);
device.DrawIndexedPrimitive(PrimitiveType.TriangleStrip,
                            baseVertexIndex,
                            0,
                            vertexCount,
                            startIndex,
                            primitiveCount);
effect.EndPass();

effect.End();
device.SetRenderState(RenderState.FillMode,
                      FillMode.Solid);
device.SetRenderState(RenderState.CullMode,
                      Cull.None);

```

# Answer
> 0 votes
After much debugging and understanding the code I found that the rendering code was correct but while creating the Viewport of the device I forgot to set the Min & Max Depth of it. In SlimDX they are set by default but in SharpDX you need to set them explicitly, this solves my issue. Thank you all for the help.

---
Tags: directx9, sharpdx, slimdx
---