# Question
Title: How can I add left and right movement to my sprite without reducing forward movement?
I've made a character sprite that moves left and right when I press A and D, and moves forward automatically. However, whenever the character moves left or right, the forward movement is greatly reduced. Does anyone know a solution?

Here is my blueprint

# Answer
When you hit the arrow keys, you are traveling the same speed, but you are pointing the sprite in a different direction. The sprite's movement is based on what direction the sprite is pointing, not a fixed direction on your screen. So your sprite is still moving forwards at the same speed, but forwards the direction it is pointing, not forwards along a certain axis on the screen.

Imagine you are driving a car down a street at a certain speed. You then steer to the left. Your car is still going the same speed forwards in the direction the car is pointing, but the distance you go down the road while steering will be less. That's because your car is spending more time traveling sideways to the street than longways down the street.

You could get all fancy and do vector math to speed up the sprite to keep forwards motion the same when turning, but it is a lot easier if you just calculate X and Y offsets yourself and not rely on vectors.

Assuming that X is side to side, and Y is forwards, it would be something like this in pseudo-code.

```
// dx is how fast you are moving side to side.  Initially zero, so no movement
dx = 0;
// dy is how fast you are moving forwards
dy = 1;

// Main game loop
while (true) {
   if (left_arrow_down) {
      // Left arrow down so move left
      dx = -1;
   } else if (right_arrow_down) {
      // Right arrow down so move right
      dx = 1;
   } else {
      // No arrow down so just move forwards
      dx = 0;
   }

   // Move sprite based on current arrow keys and forwards motion
   sprite_x = sprite_x + dx;
   sprite_y = sprite_y + dy;

   // Now redraw the sprite at this  new location
   draw_sprite(sprite_x, sprite_y);
}

```

With this kind of approach, any side to side motion will not slow down the forwards motion. Sorry I don't know Unreal enough to create a blueprint for this, but you should be able to translate this concept into a blueprint.
> 1 votes

# Answer
Try summing everything in a tick event.
> 0 votes

---
Tags: movement, input, unreal-4, blueprints
---


# Question
Title: OnCollisionEnter2D just flat out not running for certain objects
I am working with the Unity3D Engine in 2D mode. Currently I am trying to make a circle collider bounce off of a composite collider for the walls of my game. The only issue is that for some reason the OnCollisionEnter2D function does not seem to even trigger when the circle collider hits the walls. I have used the log to determine this. I am curious as to why it has this behviour, since it does end up triggering when the player contacts the circle collider? Here is the important parts of the script:

```
public class sword : MonoBehaviour {

public Rigidbody2D rb;
public CircleCollider2D coll;

public float speed;
public Vector2 trajectory;
public GameObject Player;

// Use this for initialization
void Start () {
    speed = 0.0f;
    anim = Player.GetComponent<Animator>();
}

private void OnCollisionEnter2D(Collision2D collision)
{
    Debug.Log("collided");
    if (collision.gameObject.tag == "player")
    {
        transform.position = new Vector2(-1000, -1000);
        Player.GetComponent<movement>().equipped = true;
    }
    if (collision.gameObject.tag == "solid")
    {
        ContactPoint2D otherObject = collision.contacts[0];

        Vector2 hit = otherObject.point;
        Vector2 normal = otherObject.normal;
        trajectory = Vector2.Reflect(trajectory, normal);

    }
}

private void FixedUpdate()
{
    //constantly calculating new velocity
    rb.velocity = speed * trajectory;
    speed = speed * 0.93f; //drag
    if (speed < 0.0001f)
    {
        speed = 0.0f;
    }
    if (speed > 1)
    {
        Physics2D.IgnoreCollision(Player.GetComponent<CircleCollider2D>(), coll, true);
    }
    else
    {
        Physics2D.IgnoreCollision(Player.GetComponent<CircleCollider2D>(), coll, false);
    }
}
}

```

More Details: My speed variable is set from a separate script, in case you are wondering. Everything is on the layer 0.. The Rigidbody for player is dynamic, for the ball it is kinematic, and for the walls it is static. Also here is an image of what the game screen would look like, I've labelled the walls and the circle collider (used for a sword).

Thank you.

# Answer
> 0 votes
So I figured out the issue. It was that the RigidBody on the ball needed "Use full Kinematic Contacts" selected. Now the object collision and reflection works as intended. The only issue now is that the object overlaps with the wall by the velocity for 1 frame before it is seen as "entered" and therefore phases into it a little. This causes a huge issue when it bounces, while still being phased into the collider, and hits another wall. Since it hasn't technically left the collider, OnCollisionEnter2D does not activate when it hits the nearby wall, causing it to simply pass through. The collision detection issue is solved, so I will try to work out this new issue myself or create a different question. Thanks for hinting me that it may be in the RigidBodies.

---
Tags: unity, 2d, collision-detection, physics
---


# Question
Title: How to unlock transform on bone - to move it, not just rotate?
I was trying to create IK constraint following a Nathan Vegdahl tutorial, and everything was nice and shiny, until I tried to actually move a bone. It's not moving, only rotating. I see that transform lock panel on location is grey and completely locked, and I have no idea what's wrong.

# Answer
What you see is normal behaviour. A bone is defined by two points, the head and tail (also called root and tip).

When a bone is connected to its parent bone, in pose mode you are unable to move the head, you can only rotate the bone so that its tail is in a different location.

To move the head of the bone you need to rotate its parent bone so that the connecting point is in a different location.

Blender provides user feedback by fading out the location of the bone when you can't directly edit that property using the current selection.
> 1 votes

---
Tags: blender, rigging, bones
---


# Question
Title: Problem with camera drag and draggable UI elements
I implemented my camera drag using the following method:

```
 if (Input.GetMouseButtonDown(0))
        {
            dragging = true;
            followPlayer = false;
            oldPos = transform.position;
            panOrigin = Camera.main.ScreenToViewportPoint(Input.mousePosition);
        }

        if (Input.GetMouseButton(0))
        {
            Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition) - panOrigin;
            transform.position = oldPos + -pos * panSpeed;
            transform.position = new Vector3(Mathf.Clamp(transform.position.x, xMin, xMax), Mathf.Clamp(transform.position.y, yMin, yMax), transform.position.z);
        }

        if (Input.GetMouseButtonUp(0))
        {
            dragging = false;
            //  followPlayer = true;
        }

```

But i also have draggable UI components that implement the `IBeginDragHandler, IDragHandler, IEndDragHandler` interfaces. Problem is of course while draging the item in the canvas the camera still moves. Any idea how to solve this besides the obvious setting of bools in the inplementation of the interfaces to prevent the camera drag code from executing. An other problem is that I have other non UI object in the game that I want to click so implementing a transparent UI element behind all other UI will not work for me.

# Answer
Problem is of course **while dragging** the item in the canvas the **camera still moves.**

So If you want separate the two dragging operation , you should define conditions like this:

```
if(click on UI) Drag UI
if(click on Objects) Drag Camera

```

I used `EventSystem.IsPointerOverGameObject` for detecting UI elements

> **Description**
>
> Is the pointer with the given ID over an EventSystem object? https://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html

Attach this Script to your Camera:

```
using UnityEngine;
using UnityEngine.EventSystems;

public class CameraDragable : MonoBehaviour
{
    public float panSpeed = 20;
    public Vector2 XLimit = new Vector2(0,50), YLimit = new Vector2(0, 50); // xMin , xMin & yMin , yMin
    public Vector3 oldPos, panOrigin;
    public bool DragUI;

    void Update()
    {
        // Check if the mouse was clicked over a UI element
        if (EventSystem.current.IsPointerOverGameObject() && Input.GetMouseButtonDown(0))
        {
            Debug.Log("Clicked on the UI");
            DragUI = true;
        }

        if (Input.GetMouseButtonDown(0))
        {
                oldPos = transform.position;
                panOrigin = Camera.main.ScreenToViewportPoint(Input.mousePosition);
        }

        if (Input.GetMouseButton(0) && !DragUI)
        {
            Debug.Log("Clicked on the Object");
            Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition) - panOrigin;
            transform.position = oldPos - pos * panSpeed;
            transform.position = new Vector3(Mathf.Clamp(transform.position.x, XLimit.x, XLimit.y), Mathf.Clamp(transform.position.y, YLimit.x, YLimit.y), transform.position.z);
        }

        if (Input.GetMouseButtonUp(0))
        {
            DragUI = false;
        }
    }
}

```

Attach this Script to **UI elements** that should be draggrable:

```
using UnityEngine;
using UnityEngine.EventSystems;

public class UIDraggable : MonoBehaviour, IDragHandler
{
    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("OnDrag");

        this.transform.position = eventData.position;

    }
}

```
> 1 votes

# Answer
The critical aspect is for touch screens you need to check like this:

```
if(Input.touchCount > 0)
{
    if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) return;
}

```

to stop camera control gestures

for non touch screens you simply check on mouse button down:

```
if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2))
{
    if(EventSystem.current.IsPointerOverGameObject()) return;
}

```
> 0 votes

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


title: Typical Point Light Flow?

text:
# Question
Title: Typical Point Light Flow?
## A Quick Note

This question assumes you have some knowledge about the overall rendering process and do not need clarification on rendering objects with `HLSL` and a `DeviceContext`. I use the `SharpDX` libraries to write my code in `C#` but I can read `C++` and convert it if needed.

---

## Overview

I am currently trying to create a prefab for a point light in my engine at work. I currently have a working directional light and can adapt from that if needed. Originally this post included some code from a pixel shader that I found on StackOverflow, but @DMGregory pointed out issues with it. I also attempted to follow a pixel shader supplied in the book Real-Time 3D Rendering with DirectX and HLSL (chapter 7 page 117); however, the HLSL in that seems to be a bit outdated since I can't use the following functions:

* `lit`
* `get_vector_color_contribution`
* `get_scalar_color_contribution`

These seem to be no longer supported with `ps_5_0` (the `HLSL` won't compile) and I can't find any documentation that provides updated equivalents. The exact error message during compilation is:

> error X3004: undeclared identifier 'get\_vector\_color\_contribution\`.

This same message is presented with all three functions.

When I attempted the pixel shader found on StackOverflow, it didn't do what I expected. I eventually discovered that this is because it wasn't sampling textures. Correcting that is simple enough, but this would have to be applied per object and makes it difficult for multiple point lights. This doesn't really fit my idea of simplicity.

---

## My Idea

I would prefer to create a point light shader that is applied to all objects capable of being illuminated in a single pass; however, I fear this isn't possible or would be incredibly difficult to achieve.

Since it is a lot of code to show the entire process, I will just include a couple relevant samples and hopefully that will help shed some light on what I currently do when rendering objects:

```
public class SceneObject {
    public Vector3 Position { get; set; }
    public PixelShader PixelShader { get; set; }
    public virtual void Render() { }
}
public class PointLight : SceneObject {
    public float Radius { get; set; }
    public float Intensity { get; set; }
    public Color Diffuse { get; set; }
    public Color Ambient { get; set; }
    public Color Specular { get; set; }
}
public class Scene {
    private void ChangeShader(SceneObject obj, bool setToCurrent) {
        if (setToCurrent)
            currentPixelShader = context3D.PixelShader.Get();

        if (currentPixelShader.DebugName != obj.PixelShader.DebugName)
            context3D.PixelShader.Set(obj.PixelShader);
    }
    public void Render(SceneObject obj, bool renderChildren = true) {
        if (!obj.Enabled)
            return;

        if (obj is PointLight)
            SetPointLightBuffer((PointLight)obj);

        if (obj.PixelShader != null)
            ChangeShader(obj, false);

        SetObjectBuffer(obj);

        if (obj.HasTexture)
            UpdateMaterialBuffer(true);

        obj.Render();

        if (obj.HasTexture)
            UpdateMaterialBuffer(false);

        if (renderChildren)
            foreach (SceneObject child in obj.Children)
                Render(child);
    }

    ChangeShader(obj, true);
}

```

There are things missing from the code I've supplied above, but this is intentional as it is a lot of code. Each object renders itself in the appropriate way. The `Scene` class manages the `DeviceContext` and other important things such as the constant buffers used by the shaders, this allows greater flexibility for future developers instead of having to learn all of the underlying `DirectX` code, they can focus on creating objects with prefabs instead.

---

## Goal

The overall goal is to achieve the most simplistic implementation of a point light that I can get, to where any object that is capable of being illuminated is illuminated when in range of the light. I believe this is going to be a post process pixel shader, but I could be wrong.

---

## Question

What is the step by step (proper) process for rendering a point light object into a scene?

---

## Note

I don't really need code samples to answer this question unless the supplied shader is incorrect. I can figure the code out, so long as you're detailed enough about the process in your answer.

# Answer
> 0 votes
It looks like you're trying to just throw your light in with a jumble of other scene objects, rendered in some arbitrary order without any knowledge of one another.

Because illumination isn't an "object" per se, but an effect on the surfaces of other objects, it needs to be handled separately. Either the objects need to know about the lights, or the light needs to be able to query information about the objects.

There are two common routes to incorporating lighting: forward and deferred. Lots more specialized variants have been developed based on these, but knowing these core concepts will give you a foundation for understanding the other techniques.

## Forward Rendering

In Forward Rendering, you incorporate illumination as you render each object.

So the shader for the object will expose some uniforms (or reference a data buffer) containing information about the lights shining on that object. In your rendering loop you'd check which lights illuminate each object, and populate those variables/buffers before rendering it. Then the object's shader will...

* (vertex shader)
    + transform the model's vertices into device coordinates
    + compute lighting vectors for each of the lights shining on the object
* (pixel shader)
    + sample the object's surface colour, normal map, and other textures
    + shade the result for each light
    + sum the contributions of each light into a final output colour

Advantages with this method include that it works for transparent geometry just as well as it does for opaque stuff, and you can have highly custom shader logic for each object, mixing wildly different material effects.

Disadvantages include, as you point out, it's difficult to scale to many lights. Each pass will typically have a maximum number of lights it can handle (eg. 4). When more lights affect the object, then you either need to exclude the less important lights (which can show odd discontinuities), approximate extra lights with a simpler form like spherical harmonics, or render additional passes to add-up the contributions of every light. The other downside is that overdraw can be quite high with this approach - you might spend several passes rendering lighting on one polygon, only to later cover up that polygon with a closer one that needs its own lighting.

## Deferred Rendering

In Deferred Rendering, you put off lighting until the end.

As you render each object, you're not rendering its final appearance, but rather making notes for the later lighting passes to use. Typically you'll use multiple render targets collectively called a "G-Buffer" to record, for each pixel on the screen...

* Depth
* Normal direction
* Albedo colour
* Material properties like roughness/metalness/specularity (the exact details will depend on your reflectance model)

After this G-Buffer is completely populated with all the opaque objects in the scene, you can use it to compute the light reflecting off each pixel to "splat" illumination additively onto a black-cleared background,.

For each light, you render a piece of geometry representing the light's bounds, to ensure you run the lighting shader only on the pixels the light could potentially touch (this helps control overdraw when you have lots of small lights). For each pixel it covers, you read the G-buffer and decode the world position of the surface at that pixel, shading it using the current light and outputting the light bouncing off that surface pixel toward the camera for just the one light. Adding up all those passes gives you the complete light bouncing off that pixel & reaching the camera.

Advantages with this method include that it partly decouples the complexity of your scene from the complexity of your lighting. Your lighting cost is bounded by the on-screen pixel area of your lights, rather than exploding with the vertex count of your scene. This makes it more efficient to render lots and lots of lights in high-detail scenes.

Disadvantages include that this works only for opaque geometry, since it assumes there's just one (front-most) surface visible at each pixel. Deferred renderers will often include a forward pass to handle transparent objects after the opaque scene has been fully lit. It's also more complicated to handle wildly different material logic per object this way, since the shading pass is separated from the object (typically we'll try to boil down lots of material behaviours into a set of parameters for a shared reflectance model).

---
Tags: c#, c++, directx11, hlsl
---


title: Combination Lighting Shader?

text:
# Question
Title: Combination Lighting Shader?
I am currently working on writing a shader for combination lighting. The idea behind it is to apply directional light, point light, and spot light in a single pass. I believe I can do this by:

* Calculate the color after directional light is applied.
* Calculate the color after the point light is applied.
* Calculate the color after the spot light is applied.
* Return the final color of the pixel.

I believe this will allow me to have multiple point and spot lights that effect the pixel currently being handled by the pixel shader.

I believe the math for this will be:

```
return directional + pointLight + spot;

```

However, my concern is that this will create just a solid white object and I am unsure as to how to prevent that. Maybe each portion is normalized to a specific percentage of full intensity and the result would be:

```
directional = calcDirectional() * 0.3f;
pointLight = calcPoint() * 0.3f;
spot = calcSpot() * 0.3f;
return direction + pointLight + spot;

```

But again, I am not 100% sure on this.

---

What is the proper way to additively calculate colors in this scenario?

# Answer
You just add the contributions from each light source. No normalization or reweighting required.

Think about light in the real world. If I shine a flashlight onto an object, it doesn't darken the light from the sun bouncing off of it. All I can do is light the object up more - pour on more photons, and more photons bounce off.

If you find your objects get too bright doing it this way, then you need to either...

* move to an HDR system and tonemap the resulting out-of-range colours back down into your device's representable range at the end (games that have a high contrast and simulated eye adaptation between dark interiors and bright exteriors often work this way), or
* reduce the intensity of your lights / make their falloff sharper so you get less total light landing on the object.
> 1 votes

---
Tags: hlsl, fragment-shader
---


# Question
Title: Adjusting view matrix when glViewPort & resizing
I have an issue when my window resizes.

I have a simple MVP shader like this

```
gl_Position = projection * view * model * vec4(in_Position, 1.0);

```

to render a map in my game scene. The map is extremely simple that it simply offers a lane's vertex. And what I need to do is drawing it inside the window.

So I set up my MVP matrix individually, the "view" and "model" matrix remains the same because all I want to do is drawing a static map. "perspective" is the only matrix need to change since I want to have a zoom feature that I can zoom in/out by changing fovy. "perspective" is updated by calling

```
glm::perspective(glm::radians(fovy), (float)width/height, near, far)

```

and my view matrix is calculated by

```
glm::lookAt(camera_pos, camera_pos + camera_front, camera_up)

```

However, when I resize the viewport, I find everything changed. I mean by default, the resolution gonna drop when my window goes larger if I didn't do anything(like updating the glViewPort()). But the behavior I wanna achieve is like

"I could see more part of the map when I made my window size larger".

Therefore I believe that I should keep my viewport resolution same (glViewPort(0, 0, screen\_width, screen\_height)). And updating perspective matrix by changing the ratio when new window's width and height comes in. Then the final step is to update the camera's position to update view matrix. However I stuck here for a while coz I don't know how to adjust it. I believe this is a common issue but I cannot even find a source talking about it.

Do I think it the wrong way? Do I need to change Camera's position to update my view matrix to achieve the resize behavior?

Platform: Ubuntu 16.04, OpenGL3.3 , C++14

# Answer
> 1 votes
> Do I think it the wrong way? Do I need to change Camera's position to update my view matrix to achieve the resize behavior?

You are correct. The purpose of the perspective matrix is to convert 3D camera space coordinates to 2D screen coordinates.

Take a look at this graphic of a viewing frustum: http://www.real3dtutorials.com/images/img00006.jpg

The frustum represents the viewable area (what you see on the computer screen) in world space where the eye is your camera. Every parallel plane between the near and far plane represents your computer screen, so you can picture the size of the world that is on the screen by imagining a cross section that roughly intersects your world / objects .

The frustum can be fully defined by the near and far planes, the field of view, and the camera position, so you have a few options to make more of your world visible, but only one is really viable.

If you were to adjust the fov, then you would certainly see more, but having a high fov will make the world distorted. The fov determines the degree at which objects shrink in the distance, so you could see more, but it needs to be similar to the field of view of the human eye in order to look realistic and not overly distorted.

Now look at the frustum again and imagine a plane inbetween the near and far plane that roughly intersects your world. You can move the near and far planes in either direction, but the size of the plane that crosses your world remains the same, so its position on the screen would be the same.

So the only real option is to move your camera back. By doing this, the entire frustum moves back, and the plane that roughly intersects your world is at a higher distance from the camera i.e. larger.

I know it isn't the clearest explaination, but let me know if you have any questions.

EDIT:

I should add that the viewport has nothing to do with size of the frustum (visible area); the viewport just maps the 2D information from the shader (which is in normalized device coordinates from \[-1,1\]) to pixels on the screen... Think of the viewport like the scale and offset of a 2D image on a page--the image scales and moves, but the content is the same.

---
Tags: opengl
---


# Question
Title: How to filter list of all objects in Unity project, by their type?
I want to filter the list of project objects in unity, and view all objects of specific type in the project. (by type, not by name) How can I do that?

# Answer
In the search bar simply type "t:" followed by the type. also "l:" can be used for filtering by label.

If you need more control over the search, use AssetDatabase.FindAssets in an editor script. more info in the following link: https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html
> 1 votes

---
Tags: unity
---


# Question
Title: Using Reflection to access an array from a ScriptableObject in Unity
I am trying to get access to a set of stored variables inside a scriptible object in Unity. This class (SectorDeclaration) has a method to pull a variable with a string of the variables name from it:

```
public Weightings[] GetVariName(string variableName)
{
    Type this_class = Type.GetType("SectorDeclaration");
    System.Reflection.FieldInfo fieldtype = this_class.GetField(variableName);
    Weightings[] fieldFind = (Weightings[])fieldtype.GetValue(null);
    return (Weightings[])fieldFind;
}

```

Here's the error I'm getting:

`TargetException: Non-static field requires a target
System.Reflection.MonoField.GetValue (System.Object obj) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoField.cs:108)
SectorDeclaration.GetVariName (System.String variableName) (at Assets/Code/Gameplay Element/level Elements/SectorDeclaration.cs:54)
BaseGameManager.InitializeNPCSystem () (at Assets/Code/Managers/BaseGameManager.cs:87)
BaseGameManager.Start () (at Assets/Code/Managers/BaseGameManager.cs:73)`

It works until the code reaches `Weighting[] fieldFind = (Weighting[])Fieldtype.GetValue(null);` I've used this code in another area but it is not working here, I've tried with `System.object obj` but it comes up with namespace doesn't contain this type, as well as with the type I am trying to access. Honestly, not sure what's wrong. If you need more information please let me know.

# Answer
> 1 votes
The error identifies exactly what the problem is:

> TargetException: Non-static field requires a target
> System.Reflection.MonoField.GetValue (System.Object obj)

Since the field isn't `static`, that means the values of the field are stored on an *instance* of the type. So when you ask the `FieldInfo` to fetch the values for you, you need to tell it *from which instance* you want it to fetch them. (You might have a dozen `SectorDeclaration` instances in your game, and it doesn't know one from the other).

The way to give it a target from which to fetch values is the `obj` argument. As shown in the docs, you set that to `null` *only when the field you want to read is `static`*. Otherwise, it should be set to the instance you want to read from.

Assuming this method is inside the `SectorDeclaration` type, and you want the values from `this` instance, you can pass `this` as the argument:

```
Weightings[] fieldFind = (Weightings[])fieldtype.GetValue(this);

```

---

Of course, in the case where we already know what type we're fetching these values from, and it's one under our control, we could bypass the use of reflection entirely in a couple of different ways.

For instance, we could use a `switch` statement, using an `enum` to identify the different fields we might want to use (which avoids "stringly-typed" code, though you can use Enum.Parse if your source absolutely must use strings):

```
public class SectorDeclaration : ScriptableObject {

    // I have no idea what these weights represent, so I'm spitballing here...
    public enum WeightingCategory {
        LoadPriorityWeights,
        SpawnProbabilityWeights,
        BiomeDistributionWeights
    }

    public Weightings[] loadPriorities;
    public Weightings[] spawnProbabilities;
    public Weightings[] biomeDistribution;

    public Weightings[] GetWeightingsByCategory(WeightingCategory category) {
        switch(category) {
            case WeightingCategory.LoadPriorityWeights: return loadPriorities;
            case WeightingCategory.SpawnProbabilityWeights: return spawnProbabilities;
            case WeightingCategory.BiomeDistributionWeights: return biomeDistribution;
            default: return null;
        }
    }

    public Weightings[] GetWeightingsByCategory(string categoryName) {
        return GetWeightingsByCategory((WeightingCategory)System.Enum.Parse(WeightingCategory, categoryName));
    }
}

```

This will likely be substantially faster at runtime and less bug-prone than using reflection.

---
Tags: unity, c#, procedural-generation, code-reflection
---


# Question
Title: Why rotating an object only on its local X axis result in sudden 180 degrees changes in Y and Z axis rotation values
I have an object (cube) in the scene and I want it to continuously rotate on its only local X axis but suddenly while rotating on X axis its Y and Z axis rotation value goes 180 degrees for some frames, but it looks fine in the game view. Please help me to get out of this problem. It is also noted that this problem doesn't occur while rotating only on Y or Z axis. Code:-

```
    void Update () {
         transform.Rotate(new Vector3(1,0,0),
         Space.Self);
    }

```

# Answer
> 5 votes
The thing to remember about Euler angles is that they're a fiction the engine generates on demand for our sake. They're not the ground truth of how rotation is stored inside the engine (that uses quaternions), and they're arguably not a natural description of the reality of 3D rotation itself.

Every 3D orientation can be represented by an *infinite number* of different Euler angle triples - just add or subtract a multiple of 360 on any axis for instance. Or combine rotations on different axes: {x: 180, y: 180, z: 0} is equivalent to {x: 0, y: 0, z: 180}

So when you ask Unity to translate the current orientation into Euler angles, it has to pick one standard version of those infinite possibilities to return, and that means there will be discontinuities somewhere - eg. wrapping from {89.5, 0, 0} to {89.5, 180, 180} instead of {90.5, 0, 0}. There's simply no way to write a function mapping orientations to angles that doesn't have a wrap-around anywhere.

The good news is that these still represent the orientation you expected to have, just written in a different way - like when a friend gives someone directions to a place that's different than the route you'd have chosen, but still gets them where they intended to go. ;)

This can cause trouble when we have code that's looking for specific Euler angle values, but the more robust solution there is to not write code that looks for specific Euler angle values. (Sorry, I know that sounds glib, but after answering gamedev questions here for a few years, I've found that code that does checks or math on Euler angles almost *never* does what its author intended for all cases that can arise in gameplay - Euler angles are very good at misleading gamedev intuition)

If you're experiencing a specific bug due to this wrapping behaviour, try asking how to solve the gameplay consequences of that bug - including the relevant code that's reading these Euler angle values - and we may be able to recommend a more robust way to phrase that code.

---
Tags: rotation, vector
---


# Question
Title: How can I change member variable when it's passed as an argument to a method?
I am trying to use the `unitConverter` method below to change the values of `u1_1SCost` and `u1_1MCost` in my `GameController` class:

```
public class GameController : MonoBehaviour
{
     public float u1_1SCost, u1_1MCost;

     public GameController data;

     public void unitConverter(float SCost, float MCost)
     {
         if (SCost >= 60)
         {
            MCost += Mathf.Floor(SCost / 60); SCost = SCost % 60;
            Debug.Log(GameController.data.u1_1MCost);
         }
     }
 }

```

I call `unitConverter` from another script:

```
public class anotherScript: MonoBehaviour
{
    void Update()
    {
        GameController.data.unitConverter(GameController.data.u1_1SCost, GameController.data.u1_1MCost);
    }
}

```

---

At `SCost = 60`, `Debug.Log(GameController.data.u1_1MCost)` still showed 0.

However `Debug.Log(MCost)` showed 1.

How can I change `u1_1MCost`? Doesn't it change by changing `MCost`?

# Answer
> 1 votes
In C#, numeric types like `float` or `int` are what are called **Value Types**, in contrast to eg. classes which are **Reference Types**.

When you assign a value type to a variable or pass it as an argument to a method, you're assigning / passing its *value*, not a reference to the original. So for example:

```
float a = 1;
Debug.Log(a);    // Prints 1
float b = a;     // Copies the current value of a into b
b = 2;           // Sets the value of b, does nothing to a
Debug.Log(a);    // Prints 1 - a is still unchanged
Debug.Log(b);    // Prints 2 - only b got the new value

```

Compare this to a reference type like an array:

```
float[] a = new float[] {1};
Debug.Log(a[0]); // Prints 1
float[] b = a;   // Puts a reference to the same array into b
b[0] = 2;        // Changes the first element of the shared array
Debug.Log(a[0]); // Prints 2 this time!
Debug.Log(b[0]); // Also prints 2 - they're the same array, just two references to it

```

The same goes when passing a variable as an argument to a method. If it's a value type, it gets passed by value by default - the method gets a local copy of the value, and changing it won't change the original.

But, as you found, we can override this default behaviour using the `ref` keyword, which says "pass this by reference, even though you'd normally just copy the value":

```
void MakeTheValueTwo(float a) {
  a = 2;
}

void MakeTheReferenceTwo(ref float a) {
  a = 2;
}

void Test() {
  float a = 1;
  Debug.Log(a); // Prints 1

  MakeTheValueTwo(a);
  Debug.Log(a); // Still prints 1 - the method modified its local copy of a, not the original.

  MakeTheReferenceTwo(ref a);
  Debug.Log(a); // Prints 2 - the method modified the original a, since it had a reference to it.
}

```

So, if you want a method to modify the source variables passed to it as arguments, mark them with `ref` in both the method's declaration and its call site (requiring the keyword in both places ensures that this change from the default behaviour is clearly visible to readers of the code and not unexpected).

# Answer
> 0 votes
I solved this with c# "ref" keyword

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


# Question
Title: Preventing overlap in OnCollisionEnter2D
So I have successfully built a script that can determine the physics for a ball reflecting linearly off of walls, similar to pong, while the ball is using a kinematic rigidbody. The issue is when the ball hits the wall and the OnCollisionEnter2D is called, the ball has had it's position adjusted based on it's velocity such that it is phased inside the wall a tiny amount. My understanding is that this is necessary in order for the engine to recognize the collision. The ball seemingly reflects like normal, but in the uncommon event that the reflected angle allows the ball to travel while still having it's collider phased inside the wall, and the ball impacts a different surface of the wall, this 2nd impact will not result in the OnCollisionEnter2D call and the reflecting result, since technically the collider never left the wall in this time. This causes the ball to fly past the wall and off-screen.

I've tried many solutions to fix this, mainly making it so that before the bounce occurs but in the collision event, I would move the ball back to the precise location where the edge of the ball hit the edge of the wall. This would mean that the collider of the ball is in-bounds at all times and therefore no odd behavior as a result of overlapping would occur. I've yet to find a good method to do this, and I'm wondering if there is one that could be suggested to me or if there's a different solution entirely (which doesn't involve changing the ball's rigidbody from kinematic).

Below is the appropriate parts of the script I have written currently, as well as an image of what the game view looks like for visualization.

```
public class sword : MonoBehaviour {

public Rigidbody2D rb;
public CircleCollider2D coll;

public float speed;
public Vector2 trajectory;
public GameObject Player;

// Use this for initialization
void Start () {
    speed = 0.0f;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "player")
    {
        transform.position = new Vector2(-1000, -1000);
        Player.GetComponent<movement>().equipped = true;
    }
    if (collision.gameObject.tag == "solid")
    {
        ContactPoint2D otherObject = collision.contacts[0];
        Vector2 normal = otherObject.normal;
        trajectory = Vector2.Reflect(trajectory, normal);

    }
}

private void FixedUpdate()
{
    //constantly calculating new velocity
    rb.velocity = speed * trajectory;
    speed = speed * 0.93f; //drag
    if (speed < 0.0001f)
    {
        speed = 0.0f;
    }
    if (speed > 1)
    {
        Physics2D.IgnoreCollision(Player.GetComponent<CircleCollider2D>(), coll, true);
    }
    else
    {
        Physics2D.IgnoreCollision(Player.GetComponent<CircleCollider2D>(), coll, false);
    }
}

```

}

More Details: The sword in this image is what acts like the ball. My speed variable is set from a separate script. Everything is on the default layer. The Rigidbody for the ball it is kinematic, and for the walls it is static. Trajectory is a Vector2 that corresponds with the angular direction of the ball.

# Answer
Are you sure, that the OnCollisionEnter2D is not triggered? Use a print() statement or a breakpoint to make sure it is not called. I think it is BTW but you using only the first element of the collision.contacts array for your calculations. Find a way to access the second or the requried element, to get the right normals to your Reflect function.

If I am wrong, then:

You can try using triggers(just tick the isTrigger on the colliders). Then you would use OnTriggerEnter2D and maybe OnTriggerStay2D in code to check for "collisions" and stuff. Find a way to get your contact points, then. See the link for a few suggestions.

https://answers.unity.com/questions/42933/how-to-find-the-point-of-contact-with-the-function.html.

Please let me know if this way it triggers the OnTriggerEnter call!

If that does not work, and you want to go with collisions, than you can find out how much is the ball in the wall (for example raycast from the ball) and push it back by that value (in OnTriggerEnter or Stay).

You can also just simply push it back by a value of your will(1/4 of the diameter of the ball for example) when in collision. You might have to adjust the graphics of the ball to hide this hack.

You shold try and play around with all of the above, and decide which one is for your setup.
> 1 votes

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


# Question
Title: How could I get rid of these shared_ptr/weak_ptr in this entity-component architecture?
We've built an entity-component architecture that works ok for our needs, but it has something that bugs me a bit from a software engineering point of view.

We use `std::shared_ptr` and `std::weak_ptr` for the `Component`s: the `Entity` owns the component through an `std::shared_ptr`, while the `ComponentManager` and other `Component`s refer to the component through a non-owning `std::weak_ptr`.

The issue is that the components are not actually shared, and they should not be shared either. They're owned by a single entity. Having an `std::shared_ptr` there suggests that anyone can take a copy of the `shared_ptr` and own it too.

Here is a diagram of how the classes are organized:

`Entity`:

* real owner of the components through `shared_ptr`
* does not know which components it holds

`ComponentManager`:

* we call `update()` on the `ComponentManager`, which in turn calls `update()` on every component it knows about
* there is one instance per type of component; we've done it like this to have control over which components get updated first (e.g. `CmpRigidBody` updates the `CmpMatrixTransform`, and from which the `CmpGfx` is then updated)
* unofficial owners of the components through `weak_ptr`s; it's "unofficial" because it's through them that the components are updated
* `weak_ptr`s are stored in a `vector`
* once the (single) `shared_ptr` goes out of scope (e.g. when the entity gets deleted), a custom deleter tells the ComponentManager to remove the `weak_ptr` from the `vector` (this also adds confusion to this architecture)

`Component` and derived:

* holds the core of the information and performs the main operations of the component
* can reference other components through `weak_ptr` (hooked up at initialization, for now)

I strongly believe in using the right tool for the job, and although this architecture works, I'm curious to see if there are alternatives that would remove the confusion introduced by the shared\_ptrs.

Maybe this is pertinent:

* The amount of entities and components is relatively low, so we won't gain much by making efforts to keep them close together (the rendering and the physics simulation are taking most of our frame time).
* We use this approach because of the re-usability offered by the components and entities from project to project.
* The project is single-threaded.
* The action takes place in the `Component`, not in the `ComponentManager` (i.e. it's a entity-component architecture, not an entity-component-system archiecture), so the `Component` needs access to other `Component`s if they still exist, and these can be removed at any time.

I could use a kind of handle system through the `ComponentManager` and query the appropriate one every time I need an access to a `Component`, but this adds a dependency... (Maybe that's the price to pay..?!)

Do I have other options?

# Answer
> 1 votes
If there is a single owner and you can properly handle clearing dangling pointer it is fine to use `unique_ptr` for the owner and raw pointers for the non-owners.

You shouldn't be allocating separate components like that. This is a cache nightmare. Especially when you combine it with virtual function calls. Once the order of components is somewhat randomized due to add and remove churn the branch predictor will no help at all and you will hit cache misses a lot when trying to call `update()` on every component.

Instead put all components of the same type into a separate vector. And use a non-virtual function to update them.

```
foreach(CmpGfx& comp: manager.getGraficsComponents()){
    updateGfx(comp);
}

```

This lets it get inlined which in turn allows for interleaving of each iteration and further optimizations.

Even better if you can fix the index per entity then you don't need to keep a pointer in the Graphics component to the matrix component.

```
foreach(std::tuple<CmpGfx&, CmpMatrix&> comp: manager.getComponents<CmpGfx, CmpMatrix>()){
    updateGfx(comp.get<CmpGfx&>(), comp.get<CmpMatrix&>());
}

```

---
Tags: c++, entity-component
---


# Question
Title: Help me adjust this RPG logarithmic leveling formula!
I'm trying to find a formula that's fits the way I want my player to gain experience and level up. I know this is primarily opinion based but I hope someone can help me!

I've used the following formula as a base, I found it here:

```
//Calculate level
Level = Math.Max( Math.Floor(6.7f * Math.Log(Experience + 455f) + -40f), 1 );

//Calculate experience for level
Experience = (long)(Math.Exp((Level - -40f) / 6.7f) - 455f);

```

I wrote a script that will show what it will look like, which is this:

I want to find a way to make it very easy for the player at early levels (let's say until level 15~), and then slowly harder. I'm not sure how to change the formula or if it's even possible! Hope you can help!

# Answer
> I want to find a way to make it very easy for the player at early levels (let's say until level 15~), and then slowly harder. I'm not sure how to change the formula or if it's even possible! Hope you can help!

There are too many ways to approach this, I don't think anyone can give a concrete answer without know more about your game, but here are some ideas:

* Make it "easy" for someone to gain levels is subjective. Depending on the game, the dungeons (for example) that are meant for players level 1-15 could have monsters that give a lot of experience, while the rest of them give less experience (For example).
* Your formula has some magic numbers, I'm not sure I can see the pattern behind them, but you can treat your formula like an interpolation. In linear interpolation, you go from A to B in equal steps, but you can use an exponential interpolation, that starts slow, and then goes faster. An example formula is `x*x` and looks like this

Example:

```
total_experience = experience;
x = your_formula_for_exp_to_next_level;
experience_to_level = x*x;

```

This will take your already existing formula, and tweak it in such a way that all values will now need less experience in the beginning, and increasingly more at the end. To increase the curve and make it so that it needs less and less experience in early levels, just keep multiplying that by `x`

For example, the interpolation `x*x*x` looks like this:

Unfortunately I can't give a more concrete answer than this, because each game has multiple ways to tweak difficulty, by giving more monster to the player, awarding more experience, giving more equipment etc etc. Hope this can help to get you started.
> 1 votes

---
Tags: c#, mathematics, rpg
---


title: Contracting Unity EditorWindow UI

text:
# Question
Title: Contracting Unity EditorWindow UI
How can I make scalable(contracting) EditorWindow UI(not in-game UI) like in inspector example?

# Answer
When speaking about the UI, all objects have a `RectTransform` instead of a `Transform`. One of it's values is the `Anchors` one. An anchor basically defines where the child is "attached" in relation to it's parent. Each object has 2 anchors, Min (for bottom-left corner) and Max (for top-right). Their values go from 0 to 1, which signifies the percentage of the screen width/height.

If for example you've set both anchors like this:

```
anchorMin.x = 0.1;
anchorMax.x = 0.9;

anchorMin.y = 0.1;
anchorMax.y = 0.9;

```

And the `RectTransform`'s positions are all 0, then all edges of that object will be 10% away from the edge of the screen, regardless of screen size (The object basically stretches from 10% to 90% of screen size).

Keep in mind that if both `x` or `y` of both anchors are the same value, the Inspector changes, and gives you a new "width" or "height" field, which you can use to give a specific size to your element. So with this example:

```
anchorMin.x = 0.1;
anchorMax.x = 0.9;

anchorMin.y = 0.5;
anchorMax.y = 0.5;

```

This object is now stretching only horizontally from 10% to 90% of screen space, and it's also anchored vertically in the middle of the screen, but on a single point. This means you can give it your own height (for example 100px) and the object will now stretch to fit the screen horizontally, while keeping itself at 100px height.

See also, Unity: Basic Layout and Unity: Designing UI for Multiple Resolutions
> 0 votes

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


# Question
Title: How do I properly link an OrthographicCamera to a OrthogonalTiledMapRenderer
how to properly link an OrthographicCamera to a OrthogonalTiledMapRenderer

How do I properly link an OrthographicCamera to a OrthogonalTiledMapRenderer? I have tiled map i'd like render and two stages that have actors on them.. I call render.render() in my screens render method as well as stages.draw(); but every i put render.setView(camera) the screen displayed flashes or does other weird things. How do I properly attach a moveable camera to a tiled map renderer? I render the map first, do game logic and then call draw on the stages. when I call translate on the camera the tiled map zooms way out for some reason?

here is my render method

```
public void render(float delta) {

    Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        renderer.render();

        gameLogic();

        backStage.act(); // acts are called but do nothing

        frontStage.act();

        frontStage.draw();
        backStage.draw();

}

```

here is where the camera and renderer get created

```
public void addMap(GameMap map){

this.map=map;
maps.add(map);
    renderer=new OrthogonalTiledMapRenderer(map.getTiledMap(), 1/20f);
    camera= new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    float aspect = Gdx.graphics.getWidth()/Gdx.graphics.getHeight();
    camera.setToOrtho(false, 20*aspect, 20*aspect);

    renderer.setView(camera);
    frontStage= new Stage();
    backStage=new Stage();

    xSize=map.getXSize();
    ySize=map.getYSize();
    Gdx.input.setInputProcessor(this);

}

```

# Answer
> 0 votes
I solved my problem I took someones working code to make the camera move which was 100% the same as mine made a new class tried running it . It worked!! Then I slowly added more of code testing each time until I was 100% of my previous code that did not work. The only thing I changed is I now have a new source code file (the class name is still the same though). Making a new class solved with the same code solved my problem?????

---
Tags: libgdx, tiled, scene2d
---


# Question
Title: In LIBGDX how to give different frametime to animations
As of now I've been using Gdx.graphics.getDeltaTime() to achieve this but I think this shouldn't be the correct way.

Let's say I have 3 images/sprites and I want the first one to stay for 1 second, the second sprite for 0.5 second and the third sprite for 3.5 seconds, so it combines a 5 second animation.

As of now I've been using "ifs", as in

if time \<= 1 second, draw first image

if time \> 1 && time \<= 1.5, draw second image

if time \> 1.5 && time \< 5, draw third image

I've followed 2D Animation tutorial, but to run multiple sprites in order, they all have the same time between them and I want it to have different frametime.

Any idea that might I would be apreciated.

The idea is to run timed based animations for a certain amount of time.

# Answer
> 0 votes
Why not implement your own class? :)

```
/**
* type T: The type of frame to display (Texture, Sprite, etc.)
*/
class TimedAnimation<T> {
    private T[] frames;
    private float[] frameTimes;

    public TimedAnimation(T[] frames, float[] frameTimes) {
        this.frames = frames;
        this.frameTimes = frameTimes;
    }

    /** Returns the frame that should show after timeElapsed seconds. */
    public Optional<T> getFrame(final float timeElapsed) {
        float counter = timeElapsed;
        float index = 0;
        while(counter > frameTimes[index] && index < frames.length) {
            counter -= frameTimes[index];
            index++;
        }
        return index < frames.length ? Optional.of(frames[index]) : Optional.empty();
    }
}

```

Assumes some things, namely that the size of `frames` and `frameTimes` is equal and that `timeElapsed` is never greater than the total time of the animation. Removing these limitations is practice for the reader ;)

# Answer
> 0 votes
One way to achieve variable length frames whilst still getting away with only using standard **libGDX** functionality would be to insert the same frame multiple times in the animation sequence:

```
TextureRegion firstImage  = /* loaded somehow */
TextureRegion secondImage = /* loaded somehow */
TextureRegion thirdImage  = /* loaded somehow */

TextureRegion[] frames = new TextureRegion[] {
  /* 2 x 0.5 = 1.0 second */
  firstImage, firstImage,
  /* 1 x 0.5 = 0.5 seconds */
  secondImage,
  /* 7 x 0.5 = 3.5 seconds */
  thirdImage, thirdImage, thirdImage, thirdImage, thirdImage, thirdImage, thirdImage
};

Animation<TextureRegion> animation = new Animation<TextureRegion>(0.5f, frames);

```

In cases like the one above where it's easy to figure out an animation frame time and the split between the frames this approach is doable, for complex frame time relations it might be harder.

One advantage is that you get all the functionality of `Animation<T>` such as `PlayMode`.

---
Tags: libgdx, animation
---


# Question
Title: Can I use glTranslate and glRotate when my GLSL Version over (#version 120)?
I was using "GLSL Version #120". But now i am trying to do one tutorial and it is using "gl\_ClipDistance\[0\]" inside of vertex shader. And "GLSL Version #120" doesn't support "gl\_ClipDistance\[0\]". Now i need to change GLSL Version with over #120 for example #330 . I also have to change "gl\_ModelViewProjectionMatrix" inside vertex shader. But my question is i need to change glTranslate,glRotate,glLoadIdentity etc ?

# Answer
Yes, you can use them, but OpenGL will not automatically transfer the resulting matrix to your GLSL, and the older built-in uniform will not be available.

What this means is you'll need to use a glGet to retrieve the matrix to your program code, followed by a glUniform to send it to your shader.
> 1 votes

---
Tags: opengl, glsl
---


title: Why are my animations flickering?

text:
# Question
Title: Why are my animations flickering?
My animation is supposed to be used in my physics project I am making. I am using 10 millisecond `setInterval()` and `setTimeout()` and it glitches in and out. The `setTimeout()` handles the `clear()` function in my code, but I have the `setTimeout()` at 9 milliseconds and it works the best. If someone can help me, here's the code:

```
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var x = 10
var y = 0
var xPos = 0
var yPos = 0

function updateVariables() {
    x = x * 0.9
    y = y * -0.9
    y = y + 1
    xPos += x
    yPos += y
}

function clear() {
    ctx.clearRect(0,0,600,600)
}

function Draw() {
    ctx.fillRect(xPos,yPos,20,10)
    ctx.fillRect(0,131,600,20)
    setTimeout(clear, 9)
}

function collisionCheck() {
    if (yPos > 120) {
        yPos = 120
    }
}

function keyCheck() {
}

setInterval(Draw, 10)
setInterval(updateVariables, 1)
setInterval(collisionCheck, 10)
```

```
<canvas id="canvas"></canvas>
```

# Answer
> 1 votes
Your timeouts do not necessarily have to match up, i.e. a timeout of 10ms might not take exactly 10ms. You are also not considering the window's refresh rate at all. You might want to google "html5 canvas game loop" for ideas on how to restructure your game loop to function better and to help you expand upon your project, however, here's a basic example of your code restructured to remove the flickering:

```
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var x = 10
var y = 0
var xPos = 0
var yPos = 0

function updateVariables() {
  x = x * 0.9
  y = y * -0.9
  y = y + 1
  xPos += x
  yPos += y
}

function clear() {
  ctx.clearRect(0,0,600,600)
}

function Draw() {
  collisionCheck();
  clear();
  ctx.fillRect(xPos,yPos,20,10)
  ctx.fillRect(0,131,600,20)
  window.requestAnimationFrame(Draw)
}

function collisionCheck() {
  if (yPos > 120) {
    yPos = 120
  }
}

function keyCheck() {}

window.requestAnimationFrame(Draw)
setInterval(updateVariables, 1)
```

```
<canvas id="canvas"></canvas>
```

The main difference here is the usage of `window.requestAnimationFrame`, which will get called everytime the window is redrawn.

---
Tags: animation, html5, html-canvas
---


# Question
Title: Calculate heading required to turn ship so that its weapon can fire at target
I have a ship, the ship travels towards a heading (vector3, blue arrow) with an arbitrary speed.

The ship has a weapon on the side, the weapon can point in any direction, except straight forward/backwards from the ship heading. (In example image the weapon is a perpendicular 90\* right).

The weapon has a firing arc, in n degrees (so, n/2 degrees in either side from the weapon "point direction").

Given a target at any position on the same side of the ship as the weapon (red circle), how do I rotate the ships heading so that when oriented towards the new heading (in this example, the yellow arrow), the target is inside the bounds of the firing arc? (The ship cannot rotate on the spot, it turns by driving forward towards a heading, like a simplified aircraft)

While my game is set in full 3D, I think a 2D solution will be more than enough. I use Unity, and C#, but I'm thankful for any solutions.

Edit: To clarify, I am looking for the "math-based" solution, collision-checks etc isn't really feasible.

# Answer
> 1 votes
This will basically boil down to math.

Unless your ship moves in the meantime, then there is a really easy approach: just let the ship turn at max turn rate and check every now and then if the target is inside the fire angle (using collision detection between the target and the area that your green lines draw up.

If not, and you want to know the necessary new heading , you have to set up the corresponding equation, which is: \[In assumption that your ship hat 1 discrete center from which *everything* is calculated\]

**new heading b2 =** **the angle between g1** (the left green line, if the target is left of the fire cone) **and t1** (which is the line drawn from the target to the center of the ship) **added to b0**

Getting the angle between vectors should be rather trivial, as well as modifying a vector by an angle. Maybe there is a way to bypass angles altogether by using normalized vectors or something, but to be honest, I slept during that part of math class. \[Also you might have to double check where what has to be added vs subtracted, because that all depends on where what is etc\]

---
Tags: unity, rotation, vector
---


title: Unity : Post Processing without playing

text:
# Question
Title: Unity : Post Processing without playing
I have attached a post processing profile to my main camera for bloom and other similar effects. I know that when the game is running, the post processing works as I can see its effects. However, is there a way for me to see my post processing effects **without** having to run the game?

# Answer
> 0 votes
Make sure that the Camera that has the `Post Process Layer` component attached is indeed your *Main Camera*. This is the camera that is used for rendering the scene view.

Under Unity terms, the main camera is the first encountered GameObject that is tagged **MainCamera**. So ensure there isn't any other such tagged camera that is found by Unity firstly.

Hope this helps!

---
Tags: unity, post-processing
---


# Question
Title: How to geographically locate the position of character on a map?
Beyond the different coordinates systems (x/y, ...), imagine you draw the map of your world on a bitmap, png, gif or whatever image.

Then you got your world and you'd like your players/character (PC) to travel through its different parts (lands, regions, etc...).

How can I simply locate in which part (land, region, ...) of the world a PC is entering/leaving ? Detecting when a boundary is crossed ?

What is the easiest way ? What options do I have ?

# Answer
> 2 votes
Define a surjective function from the game coordinate system to the world map.

Suppose we have a game world where all points are between (0, 0) and (100, 100). We can then create a world map that is 10 pixels by 10 pixels and a function f(P) = (P\_x / 10, P\_y / 10) to map from the game world to the world map.

Let's suppose that we want more detail on our world map so instead of a single 10x10 world map, we create 100 10x10 world maps. First we determine which world map to use, WM(P) = (P\_x MOD 10, P\_y MOD 10), then we determine where on that world map we are, f(P) = (P\_x - 10 * (P\_x MOD 10), P\_y - 10 * (P\_y MOD 10)).

This can be taken a step further (see World of Warcraft) where the game world is divided into larger pieces, zones, and each zone has its own world map which can be broken into pieces like the previous example.

Ultimately this is a design decision with no technical limitations imposed as part of the questions. As best method depends on your requirements, I encourage you to explore how other games have addressed this on a conceptual level and build from that.

# Answer
> 0 votes
You are not asking about "beyond" you are asking "on top". Because what you want is these regions to be mapped onto the coordinate system an then use collision detection for the borders of said regions. Then change a variable/attribute of the player object.

If your game does not have free movement but rather a "go to Wide forest", "go to city X" mechanic, a simple attribute on some object would do

---
Tags: maps, coordinates
---


# Question
Title: Spawning prefab when other prefab appears
Im trying to make a bottle spawn when it is broken.

This is the code that makes that:

```
public class romperobjetos : MonoBehaviour {

public GameObject BrokenBottle;
public float breakVelocity = 5f;
public GameObject NoBrokenBottle;
public bool rompible = false;
public Vector3 oldPosition;
public Quaternion oldRotation;
public bool botellarota = false;

public void Start()
{

}

// Use this for initialization
public  void Update()
{
    Debug.Log(NoBrokenBottle.GetComponent<Rigidbody>().velocity.magnitude);
    if (NoBrokenBottle.GetComponent<Rigidbody>().velocity.magnitude > breakVelocity)
    {
        rompible = true;
    }
    else
    {
        rompible = false;
    }

}
public void OnTriggerEnter(Collider other)
{
    if ((other.gameObject.name == "Plane") && (rompible))
    {
        oldPosition = NoBrokenBottle.transform.position;
        oldRotation = NoBrokenBottle.transform.rotation;
        Debug.Log("vamos bien");
        BreakBox();
    }
}
public void BreakBox()
{
    Instantiate(BrokenBottle, oldPosition, oldRotation);
    Debug.Log("se rompe");

        NoBrokenBottle.SetActive(false);
        botellarota = !botellarota;
}

```

}

The broken bottle prefab has a boolean variable that is **true** when it appears, but the unbroken bottle doesn't instantiate. This is the script for the spawn:

public class SpawnBotellas : MonoBehaviour {

```
public Transform[] spawnPoints;
public GameObject[] whatToSpawnPrefab;
public GameObject[] whatToSpawnClone;
public bool botella1rota = false;
// Use this for initialization
void SpawnAlgo()
{
    whatToSpawnClone[0] = Instantiate(whatToSpawnPrefab[0], spawnPoints[0].transform.position, Quaternion.Euler(0, 0, 0));
}
 void Update()
{
    //botella1
    if (GameObject.Find("alidobas blanco roto").GetComponent<alidobasrota>().alidobasblanco)
    {
        Debug.Log("asdkj");
      //  whatToSpawnClone[0] = Instantiate(whatToSpawnPrefab[0], spawnPoints[0].transform.position, Quaternion.Euler(90, 0, 0)) as GameObject;
    }

```

Sorry for my bad English and thanks.

# Answer
We can simplify this into the following psuedocode.

```
public void OnTriggerEnter(Collider other) {
    if (gameObject.GetComponent<Rigidbody>().velocity.magnitude > breakVelocity) {
        // spawn new broken bottle object at current position
        // delete this game object
    }
}

```

Having the broken and unbroken bottle be seperate MonoBehaviours gives a number of advantages. One is keeping the logic for a broken and unbroken bottle seperate, reducing complexity. Another is that when addressing a broken or unbroken bottle, you can check object type instead of object state, this will likely result in less coupling.
> 0 votes

# Answer
I managed achieve it doing the script that instantoiates broken bottle instantiate the nice bottle too

```
public GameObject BrokenBottle;
    public float breakVelocity = 5f;
    public GameObject NoBrokenBottle;
    public bool rompible = false;
    public Vector3 oldPosition;
    public Quaternion oldRotation;
    public bool botellarota = false;
    public Transform[] spawnPoints;
    public GameObject[] whatToSpawnPrefab;
    public GameObject[] whatToSpawnClone;

    public void Start()
    {

    }

    // Use this for initialization
    public  void Update()
    {
        Debug.Log(NoBrokenBottle.GetComponent<Rigidbody>().velocity.magnitude);
        if (NoBrokenBottle.GetComponent<Rigidbody>().velocity.magnitude > breakVelocity)
        {
            rompible = true;
        }
        else
        {
            rompible = false;
        }

    }
    public void OnTriggerEnter(Collider other)
    {
        if ((other.gameObject.name == "Plane") && (rompible))
        {
            oldPosition = NoBrokenBottle.transform.position;
            oldRotation = NoBrokenBottle.transform.rotation;
            Debug.Log("vamos bien");
            BreakBox();
        }
    }
    public void BreakBox()
    {
        whatToSpawnClone[0] = Instantiate(whatToSpawnPrefab[0], spawnPoints[0].transform.position, Quaternion.Euler(-90, 0, 0)) as GameObject;
        Instantiate(BrokenBottle, oldPosition, oldRotation);
        Debug.Log("se rompe");

            NoBrokenBottle.SetActive(false);
            botellarota = !botellarota;
    }
}

```
> 0 votes

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


# Question
Title: 18.5:9 Android ratio force to 16:9 problem in Unity
I want to my game build in devices with 18.5:9 ratio like Samsung S8 forced to be displayed as 16:9 ratio. I already set Aspect ratio mode to Custom and set it to 1.86 in Player Settings. I also overrided Android Manifest like this:

```
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.unity3d.player" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal">
    <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
    <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:isGame="true" android:banner="@drawable/app_banner">
  <activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name" android:screenOrientation="sensorLandscape" android:launchMode="singleTask" android:maxAspectRatio="1.86" android:resizeableActivity="false" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false">
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
    <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
  </intent-filter>
  <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
  </activity>
  <meta-data android:name="unity.build-id" android:value="633a700a-7389-4a19-972c-ac1f177788f8" />
  <meta-data android:name="unity.splash-mode" android:value="0" />
  <meta-data android:name="unity.splash-enable" android:value="True" />
  <meta-data android:name="android.max_aspect" android:value="1.86" />

  </application>
  <uses-feature android:glEsVersion="0x00020000" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-feature android:name="android.hardware.touchscreen"
android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch"
android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
  </manifest>

```

And as you see add attributes like android:maxAspectRatio & android:resizeableActivity to AndroidManifest manually.

But by installing the app on devices with that specific ratio, the game still running full screen and out of the bounds. I am using Unity 2018.1.4f1 (64bit).

# Answer
> Another thing to note is that Samsung phones tend to remember if your app was opened in "full wide screen" and even modifying the manifest may still open them in "full wide screen" (there should be a toggle in settings for each installed app which allows choosing whether the app should use a full screen or just a 16:9 aspect part of it).

As the above sentences said (from this topic), Android will override manifest and we cannot control whether the app is running Full Screen or not on devices by this ratio. So I found we should edit Canvas functionality to be Full Screen with black space each side in this ratio (this comes when the design of the game was based on 16:9).

In Canvas Scaler component from UI Canvas, my setting was like this :

That means UI must fill Width of device that runs on it, without considering Height. That will work on normal ratios, but for ratios like Samsung S8 or Pixel 2 XL, we must tune Match variable to make height of the game match by height of the device screen.

Of course, this is a temporary solution and we must change our design to it can be full screen even on this wide ratios.
> 0 votes

---
Tags: unity, android
---


# Question
Title: Creating structure to a game (Missions, Dialogue, Triggering events upon items collected, etc) & monitoring the progress of a player in our code?
Hello all I have been working with Unity and other game engines/libraries for many years in my spare time. It's been a long twisty road full of joy and pain :D In the last few months or so I have been jumping back in and noticing I really have a good grasp of the basics for almost all aspects of game development (in other words I can happily make little characters move on input in several ways with rigidbody, without rigidbody; Animations I have an ok understanding with; shaders and skyboxes and post processing I kind a barebones knowledge of, etc).

My main issue I always come unstuck with (and end up defeated until I start building a new project which just involves doing the above stuff I listed that I already kinda understand), is managing actual Quests or Special Events throughout the game.

For example, today I'm trying to make a puzzle game (similar to Monkey Island but much much more basic puzzles for now). So you start out in the game stuck inside a room, there are many items in the room , and a door and fireplace. The door is locked. To solve the puzzle you just need to use the Jug of Water on the fire, then you will be able to click the fireplace to climb out of the room.

I've actually made this exact puzzle before and it all worked (I used mainly Strings and had complicated if statements to work out if the player was holding that item). But once I applied this method across a whole game (lets say you keep the empty water jug there and need it in a puzzle way later in game along with some other items etc.) then it gets majorly complicated and seems like not a good way to do it.

I've read lots about text-data types. Apparently its possible to create my own custom commands in text files so that I can annotate the text and use that to trigger methods in my code , but whilst I have read a bit about this on a few forum posts I cannot find much help with coding this (on a very simple beginner level).

I'm hoping I can build a text file that holds items along with dialogue and mission data : Item names; Item description dialogue; Whether they are quest items; Can they be combined (and if so with what and into what);

Ideally, the same system could be used for dialogue (Initial "Hello" with NPC; follow-up conversations; does NPC give quests? if so start one; final (after all quests from this NPC complete) "See ya around!" type dialogue) The text file should be able to help me from what I've read but I dont know how?!?!?

I'm fairly well versed in Polymorphism so like an Item is the parent and then child class might be Food: Item ; Weapon: Item; Tool: Item ,etc. and I also have parsed data from text to make simple pong-breakout style levels (using Json and XML). I feel like that is the way to do it, but Im missing much about adding attributes or custom markup or something like this to my text data.

I know the query here is extremely broad but any broad helpful suggestions of where I can start would be greatly appreciated. Many thanks

# Answer
> 1 votes
Let's build a conceptual framework and then consider the implementation details.

We'll start with our basic building block, the objective. Every objective is either complete or incomplete. Objectives may have additional meta-data attached, e.g. number of items collected and number of items required. Objectives may be composed of other objectives, e.g. objective A requires objective B and objective C.

Let's consider a few examples to flush out the concept a bit. We will use a psuedo json format to represent the data, but remember the implementation does not need to mirror this!

First we want our player to aquire a weapon, we can describe the initial state as follows.

```
{
    completed: false,
    requirements: {
        weapon_aquired: false
    }
}

```

We want our player to kill 10 boars, but only after they have completed the requisite quest, acquiring a weapon. It could look a bit like this.

```
{
    completed: false,
    requirements: {
        kills_left: 10,
        acquire_a_weapon: {
            completed: false
        },
    }
}

```

How we implement this can vary widely depending on requirements. Consider an MMORPG where one could expect to maintain the state of a large number of objectives for a large number of players. It might be advantageous to encode quest completion state using a bit field and limit the number of active quests being tracked to reduce meta-data storage requirements (e.g. World of Warcraft only allows 20 active quests per player). Consider a game of rock, paper, scissors where the objective is to win two out of three games. The associated meta-data (number of wins) is relatively small even for a large number of players, encoding the objective as a JSON object can decrease complexity.

Parameters to consider include the amount of data per player you expect to track, the number of players you expect to track simultaneously, and the frequency of reads and writes. These parameters will help you determine how much meta-data to track per player and how to encode it.

---
Tags: unity, databases
---


# Question
Title: How to keep track of camera's rotation while it's being rotated?
I'm building a 2D game where the sole interaction of the player is rotating what they can see (this is currently the camera, though it could be the world) by plus or minus 60 degrees.

My current approach has their input rotating the camera. The issue I'm having is that I'm finding it impossible to keep track of how many degrees they've rotated it, since the camera is rotating and losing its initial position.

(I'm using libgdx, however, I think this problem is framework independent.)

**Edit:**

To help with the understanding, let me provide an example. Picture yourself in a school playground. You want to turn 90 degrees. To help you keep track, you mark the ground with the chalk in your hand. Turning 90 degrees is now easy since you have a reference point.

Now imagine you're in space and trying to do the same thing. Instead of chalking the ground, you chalk yourself. It's now nigh impossible to know how much you turn by when you do.

# Answer
> 0 votes
I've found an answer, but I don't consider it to be a good one because it's tied to Libgdx and not a generic approach.

Libgdx's Camera has a vector called `up` equalling (0,1,0). During testing, on rotating the camera 90 degrees to the left, I discovered this vector became (1,0,0).

In other words, the relationship between the rotated angle and this vector is (sinθ, cosθ, 0).

Again, I don't consider this to be a great solution from a mathematical perspective. I was just lucky. If anyone knows how to answer from the perspective of view & projection matrices, please do share.

# Answer
> 0 votes
Why don't you simply have a variable that stores your amount rotated?

```
private float totRot;

/** Rotate camera by the specified degrees.
 *
 * @param degrees */
public void rotate(final float degrees) {
    Vector3 axis = Vector3.Z; /* Or whatever axis */
    camera.rotate(axis, degrees);
    totRot += degrees; // Track amount rotated
}

/** Rotates the camera to the specified degrees.
 *
 * @param degrees */
public void rotateTo(final float degrees) {
    rotate(degrees - totRot);
}

```

To interpolate the rotation over time you can use a helper class (untested, constructor and getters / setters omitted):

```
public class CameraRotator {
    private Camera camera;
    private Vector3 axis;
    private Interpolation interpolation;

    private float startRot;
    private float rotAmount;
    private float totRot;

    private float rotTime;
    private float timeCounter;

    private boolean rotationFinished;

    public void update(final float delta) {
        if (rotationFinished)
            return;

        /* Increment time spent */
        timeCounter += delta;
        /* Calculate progress */
        float alpha = timeCounter / rotTime;
        alpha = MathUtils.clamp(alpha, 0, 1);

        /* Interpolate rotation using alpha (progress) */
        rotateTo(interpolation.apply(startRot, rotAmount, alpha));

        /* If (alpha == 1) we're finished. */
        if (alpha == 1) {
            timeCounter = 0;
            rotationFinished = true;
        }
    }

    /** Rotate camera by the specified degrees in the specified
     * time.
     *
     * @param degrees
     * @param time */
    public void startRotation(final float degrees, final float time) {
        startRot = totRot;
        rotAmount = degrees;
        rotTime = time;
        rotationFinished = false;
    }

    /** Rotate camera by the specified degrees.
     *
     * @param degrees */
    private void rotate(final float degrees) {
        camera.rotate(axis, degrees);
        totRot += degrees; // Track amount rotated
    }

    /** Rotates the camera to the specified degrees.
     *
     * @param degrees */
    private void rotateTo(final float degrees) {
        rotate(degrees - totRot);
    }
}

```

Of course if you don't need the interpolation over time and plan on instantly rotating the camera the first method should work just fine.

# Answer
> 0 votes
Store a unit vector for your initial facing, I. At any point in the rotation you can use the unit vector of your current facing, C. Calculate the angle between the two vectors using I \dot C = |I| * |C| * cos(\theta).

---
Tags: libgdx, camera, rotation
---


# Question
Title: Texture Atlas and HLSL Shader for sprite tiling
I am trying to create a shader that allows to tile a specific region of a texture. This seem to be a common need however I can't seem to find any information about how to get this effect done.

The closest I have found is the following article made by Renaud Bedard which detail a little bit how he got it to work. : http://theinstructionlimit.com/wrap-spritesheet-atlas

I have tried to implement his process within a complete shader without any success.

```
float3x3 Matrices_Texture;

texture ColorTexture : DIFFUSE <
    string ResourceName = "default_color.dds";
    string UIName =  "Diffuse Texture";
    string ResourceType = "2D";
>;

sampler2D ColorSampler = sampler_state {
    Texture = <ColorTexture>;
    FILTER = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct vertexInput {
    float4 Position : POSITION0;
    float2 TextureCoordinates   : TEXCOORD0;
};

struct vertexOutput {
    float4 Position : POSITION0;
    float2 TextureCoordinates   : TEXCOORD0;
    float2 UV       : TEXCOORD1;
    float2 UVScale      : TEXCOORD2;
};

vertexOutput mainVS(vertexInput input)
{
    vertexOutput output;
    output.TextureCoordinates = mul(float3(input.TextureCoordinates, 1), Matrices_Texture).xy;
    output.UV = Matrices_Texture[2].xy;
    output.UVScale = float2(Matrices_Texture[0][0], Matrices_Texture[1][1]);
    output.Position = input.Position;
    return output;
}

float4 mainPS(vertexOutput input)  : COLOR0
{
    float2 tc = input.TextureCoordinates;
    tc = frac((tc - input.UV) / input.UVScale) * input.UVScale + input.UV;
    float4 sample = tex2D(ColorSampler, tc);
    return sample;
}

technique technique0 {
    pass p0 {
        CullMode = None;
        VertexShader = compile vs_3_0 mainVS();
        PixelShader = compile ps_3_0 mainPS();
    }
}

```

Note that I have zero experience with HLSL, I tried my best to use the correct types and sementic but I still can't seem to get anywhere with this. If someone could provide additionnal information, it would be greatly appreciated.

Currently, it looks like it is tiling in the preview of the material however when applied to an object, no texture is being displayed. (Testing inside FX Composer 2.5)

# Answer
> 0 votes
Here's a version of that HLSL FX file that does what you want in FX Composer :

```
float4x4 WorldViewProj : WorldViewProjection;

texture ColorTexture;
sampler2D ColorSampler = sampler_state {
    Texture = <ColorTexture>;
    FILTER = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

float2 CellCount;
float2 CellIndex;
float2 TCRepeat;

struct VertexInput
{
    float4 Position : POSITION0;
    float2 TextureCoordinates : TEXCOORD0;
};

struct VertexOutput {
    float4 Position : POSITION0;
    float2 TextureCoordinates   : TEXCOORD0;
};

VertexOutput mainVS(VertexInput input)
{
    VertexOutput output;

    float2 cellSize = 1.0f / CellCount;
    float2 cellOffset = cellSize * CellIndex;

    output.TextureCoordinates = (input.TextureCoordinates * cellSize + cellOffset) * TCRepeat;
    output.Position = mul(input.Position, WorldViewProj);
    return output;
}

float4 mainPS(VertexOutput input)  : COLOR0
{
    float2 cellSize = 1.0f / CellCount;
    float2 cellOffset = cellSize * CellIndex;

    float2 tc = input.TextureCoordinates;
    tc = frac((tc - cellOffset) / cellSize) * cellSize + cellOffset;
    float4 sample = tex2D(ColorSampler, tc);
    return sample;
}

technique technique0 {
    pass p0 {
        CullMode = None;
        VertexShader = compile vs_3_0 mainVS();
        PixelShader = compile ps_3_0 mainPS();
    }
}

```

The main issue with the original version is that you need to multiply the object-space vertex with the World-View-Projection matrix.

Also, I find that if you're working with a spritesheet, it's more intuitive to think in terms of cell count and cell index than providing a 3x3 texture matrix, so the version I linked here reflects that.

The "TCRepeat" parameter would be the tiling of your texture coordinates in your mesh, or you could leave it there for convenience. It represents the tiling rate of your plane.

---
Tags: xna, shaders, hlsl
---


# Question
Title: Why do I get this weird shadow render error?
Using Unity 2018.2.14/15 I've recently been working on a small project and I encountered a very weird problem. It's hard to describe so here is a picture:

Originally I assumed it may be an issue with my shadow/lighting settings (I think it looks like that a lot), but I couldn't find any setting that had a direct impact on the lines.

Ignoring it sadly isn't an option and I don't know of any workaround...

Some additional information:

1. The problems are 2-3 well visible decreases in lighting brightness. It seems a bit like there is something causing automatically descending lighting quality the further away from the camera the walls are, however I haven't found a setting to change this yet.
2. Currently I'm using quads and a custom material based on the Standard Opaque Shader with an Albedo setup. I'm using a self-made Texture for the walls (and a normal map created from a grayscale/bumpmap version of the texture). However, I've also tried changing between all non-round Unity Standard Models with no result.
3. The lines are indeed dependent on Camera Distance (both Editor and ingame Camera). If I move the walls, the lines stay at the same position on the walls (like on a certain spherical radius around the camera). If I move the camera (editor and ingame camera display different lines) the lines move together with it.

Do you have any idea what's going on/what I can do to prevent those lines from appearing?

Thank you in advance! :)

# Answer
> 0 votes
So it seems that the problem was actually the auto-generated MipMap on the normal Map. At certain distances from the camera the decreased MipMap quality lead to the mentioned rendering artifacts/problems. Turning off the MipMaps (Located within the Import Settings of the Texture under Advanced -\> Generate Mip Map) solved the problem. Alternative solution: Set the Filter Mode of the Texture to Trilinear (instead of turning off the MipMap)

---
Tags: unity, rendering, shadows
---


# Question
Title: Difference between Unity's [Command] and [Server]
\[Command\] and \[Server\] functions both run on the server and can also be called by a local player but what is the difference between them?

# Answer
> 1 votes
They actually do quite different things according to the documentation:

https://docs.unity3d.com/ScriptReference/Networking.CommandAttribute.html

> \[Command\] functions are invoked on the player GameObject associated with a connection

https://docs.unity3d.com/ScriptReference/Networking.ServerAttribute.html

> A \[Server\] method returns immediately if NetworkServer.active is not true, and generates a warning on the console

But be sure to be mindful of the comment by Draco18s:

> It may not be advisable to learn UNet too deeply, it is being deprecated and replaced in the next six to 12 months

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


# Question
Title: How can I develop and publish a game when I don't have the money to buy a brand new computer?
I'd like to complete and publish a game made with Unity, but given the fact that the cost of a brand new computer represents a *significant* part of my yearly income, I don't have enough money to buy one.

My ultimate goal is to publish the game on iOS.

Aside from generating more revenue upfront, what are my options?

---

**Notes from the moderators:** We've made this question canonical, so we're looking for non-specific options (e.g. please avoid targeting specific regions, or suggesting to buy specific models, etc.); we'd like to help future visitors coming from all over the world, for the years to come.

# Answer
I see a couple options:

* Go big, but start small: You could save up for a used Windows computer, finish your game, publish it on Google Play, generate revenue from it, and use that revenue to buy a used Mac computer, then publish your game for iOS. Making games is fun, but if you spend more money on it than you make out of it, really, it's a hobby.
* If you have friends that do own a Mac, you can ask *them* to build publish your game on the iOS App Store for you.
* Another option would be to look for a games incubator. This is a company that has office space, infrastructure and support for other small companies to get going in game development. They help getting your first game out.
> 1 votes

---
Tags: unity, publishing
---


# Question
Title: Calculating normal map from height map using Sobel operator
So I'm trying to generate a normal map from a greyscale height map. Unfortunately the result I'm getting doesn't seem quite right.

Here is the height map I'm using to generate the normal map:

Here is my generated normal map:

For reference, here is the normal map that gets generated from http://cpetry.github.io/NormalMap-Online/:

One thing I notice in my normal map is that there seems to be edges. I'm not really sure why I am getting these edges - does anyone know why?

Here's the code that I'm using to generate the normal map:

```
// Source:
// https://stackoverflow.com/questions/2368728/can-normal-maps-be-generated-from-a-texture
// and
// http://www.catalinzima.com/2008/01/converting-displacement-maps-into-normal-maps/
float32 height(const std::vector<char>& data, const int width, const int height, uint32 x, uint32 z)
{
    if (x >= width)  x %= width;
    while (x < 0)    x += width;
    if (z >= height) z %= height;
    while (z < 0)    z += height;

    return static_cast<float32>(data[z*width*4 + x*4 + 3]) / 255.0f;
}

uint8 textureCoordinateToRgb(const float32 value)
{
    return (value + 1.0) * (255.0 / 2.0);
}

glm::vec3 calculateNormal(const std::vector<char>& data, const int width, const int height, uint32 x, uint32 z)
{
    const float32 strength = 8.0f;

    // surrounding pixels
    float32 tl = height(data, width, height, x-1, z-1); // top left
    float32  l = height(data, width, height, x-1, z);   // left
    float32 bl = height(data, width, height, x-1, z+1); // bottom left
    float32  t = height(data, width, height, x, z-1);   // top
    float32  b = height(data, width, height, x, z+1);   // bottom
    float32 tr = height(data, width, height, x+1, z-1); // top right
    float32  r = height(data, width, height, x+1, z);   // right
    float32 br = height(data, width, height, x+1, z+1); // bottom right

    // sobel filter
    const float32 dX = (tr + 2.0 * r + br) - (tl + 2.0 * l + bl);
    const float32 dY = (bl + 2.0 * b + br) - (tl + 2.0 * t + tr);
    const float32 dZ = 1.0 / strength;

    glm::vec3 n(dX, dY, dZ);
    n = glm::normalize(n);

    return n;
}

void calculateNormals(std::vector<char>& data, const int width, const int height)
{
    for (int i = 0; i < width; ++i)
    {
        for (int j = 0; j < height; ++j)
        {
           const glm::vec3 n = calculateNormal(data, width, height, i, j);

            // convert to rgb
            data[j*width*4 + i*4 + 0] = textureCoordinateToRgb(n.x);
            data[j*width*4 + i*4 + 1] = textureCoordinateToRgb(n.y);
            data[j*width*4 + i*4 + 2] = textureCoordinateToRgb(n.z);
        }
    }
}

std::unique_ptr<Image> generateFormattedHeightmap(const Image& image)
{
    std::vector<char> data;
    int width = image.width();
    int height = image.height();

    data.resize(width*height*4);

    if (image.format() == Image::Format::FORMAT_RGB)
    {
        int j=0;
        for (int i=0; i < data.size(); i+=4)
        {
            data[i] = image.data()[j];
            data[i+1] = image.data()[j+1];
            data[i+2] = image.data()[j+2];
            data[i+3] = (image.data()[j] + image.data()[j+1] + image.data()[j+2]) / 3;

            j+=3;
        }
    }
    else if (image.format() == Image::Format::FORMAT_RGBA)
    {
        for (int i=0; i < image.data().size(); i+=4)
        {
            data[i] = image.data()[i];
            data[i+1] = image.data()[i+1];
            data[i+2] = image.data()[i+2];
            data[i+3] = (image.data()[i] + image.data()[i+1] + image.data()[i+2]) / 3;
        }
    }

    calculateNormals(data, width, height);

    return std::make_unique<Image>(data, width, height, Image::Format::FORMAT_RGBA);
}

```

Does anyone have any ideas?

# Answer
> 4 votes
So it looks like my problem was in the `float32 height(const std::vector<char>& data, const int width, const int height, uint32 x, uint32 z)` function.

Casting the `char` to an `unsigned char` before casting it to a `float32` fixes the issue.

Thanks to @DMGregory for pointing me in the right direction.

---
Tags: c++, heightmap
---


title: Remove hidden values within string

text:
# Question
Title: Remove hidden values within string
I tried removing the Unicode Whitespaces in the string using `words[len].Trim()` but still there's still an extra character.

Every letter represents the coordinate of where the letter is. As you can see there's an extra coordinate/value and it is always located at the end of the string. (dont mind the '# tries') Can you help me Identify what is the extra invisible unicode and what to do in order for it to be removed?

```
private string[] FisherShuffle(string[] words) {
    int len = words.Length;
    while(len > 0) {
        float index = Mathf.Floor(Random.Range(0f, 1f) * len);
        len--;
        var temp = words[len].Trim();
        words[len] = words[(int)index];
        words[(int)index] = temp;
    }
    return words;
}

```

**UPDATE:** I have found out that the ASCII value is 13. I also have tried using `TrimEnd('\n','\n')` & `words[len].TrimEnd(System.Environment.NewLine.ToCharArray())` to no avail

```
private string[] FisherShuffle(string[] words) {
    int len = words.Length;
    int index;
    string temp;
    while(len > 0) {
        index = (int) Mathf.Floor(Random.Range(0f, len));
        len--;
        //temp = words[len].TrimEnd('\n','\r');
        temp = words[len].TrimEnd(System.Environment.NewLine.ToCharArray());
        words[len] = words[index];
        words[index] = temp;
    }
    return words;
}

```

# Answer
> 1 votes
The documentation for String.Trim() tells us

> White-space characters are defined by the Unicode standard. The Trim() method removes any leading and trailing characters that produce a return value of true when they are passed to the Char.IsWhiteSpace method.

One option is to use the overload String.Trim(Char\[\]) to specify characters that you aren't expecting. To debug, you could iterate over the string printing each character and the corresponding result of `Char.IsWhiteSpace`.

Please consider refactor as well.

```
private string[] FisherShuffle(string[] words) {
    int len = words.Length;
    int i;
    string tmp;

    while(len > 0) {
        i = (int) Random.Range(0, (float) len);
        len--;

        tmp = words[len].Trim();
        words[len] = words[i];
        words[i] = tmp;
    }
    return words;
}

```

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


# Question
Title: Perspective Matrix doesn't work OpenGL 4
I tried to implement my own perspective matrix and it doesn't work. I don't understand why. With just with my view matrix (without Perspective Matrix) I can see my mesh.

Here my view matrix :

```
Vec3f position(0.0,0.0,-5.0);
Vec3f target(0.0,0.0,0.0);

Mat4f Camera::LookAt(Vec3f target, Vec3f position)
{
 //ce dont j'ai besoin pour calculer les parametre de ma camera...
 Vec3f up_world = Vec3f(0.0,1.0,0.0);
 Vec3f forward = (position - target).normalize();
 Vec3f right = up_world.cross(forward).normalize();
 Vec3f up = forward.cross(right).normalize();

 Mat3f R;
 R.setCol(2,forward);
 R.setCol(0,right);
 R.setCol(1,up);

 R.transpose();

 Mat4f R4(R);

 Vec3f mp = position * -1.0f;
 Mat4f P4;
 P4.setCol(3,mp);

 _LookAt = R4 *P4;
 return  _LookAt;
}

```

And my Perspective Matrix :

```
Mat4f Camera::perspective(float fovy, float aspect, float zNear, float zFar)
{

  float theta = fovy * 0.5f * (180.f / M_PI);
  float range = zFar - zNear;
  float invtan = 1.f/tanf(theta);

  Mat4f projMat(invtan / aspect,  0.0f,    0.0f,                       0.0f,
                           0.0f,  invtan,  0.0f,                       0.0f,
                           0.0f,  0.0f,    -(zFar + zNear) / range,  -2 * zNear * zFar / range,
                           0.0f,  0.0f,    -1.0f,                      0.0f);

    _perspectiveCam = projMat;
    std::cout << _perspectiveCam << std::endl;
    return _perspectiveCam;
}

  Mat4f perspective(float fovy = M_PI/2, float aspect = (1280.f/720.f)*1.f, float zNear = 0.1f, float zFar = 100.f);

```

My shader is very simple so it can't be the problem..

```
#version 410 core

layout(location = 0) in vec3 V_position;
layout(location = 1) in vec3 V_color;
layout(location = 2) in vec3 V_normal;

uniform mat4 view_matrix;
uniform mat4 proj_matrix;

out vec3 color;
void main()
{
    color = V_color;
    gl_Position = proj_matrix * view_matrix * vec4(V_position, 1.);
}

```

when I initialise \_perspectiveCam with the unit matrix 4x4 it displays my triangle.. but when I implement \_perspectiveCam like in the function it does not display my triangle

Here my Set col function :

```
template <typename TYPE>
void Mat4<TYPE>::setCol(int i, Vec4<TYPE>& vec4)
{
  for (size_t k = 0; k < 4; k++)
  {
    setElement(k,i, vec4.getElement(k));
  }

}

void setElement(int i,int j, TYPE var){element[i*4 + j] = var;}
TYPE getElement(int i, int j) const {return element[i*4 + j];}

```

# Answer
First off: *"It doesn't work"* is not very descriptive. What are you observing? A black screen? Distorted geometry?

Next: What is the convention for your Mat4f class? Can you show setCol() implementation? Is your translation part stored in \[3\],\[7\],\[11\] or \[12\],\[13\],\[14\]?

Because I suspect that your projmat may have flipped col/row?

In my implementation, the projmat (same values as yours) is laid out differently, like so:

```
    mout[0] = f / aspect;
    mout[1] = 0.0f;
    mout[2] = 0.0f;
    mout[3] = 0.0f;

    mout[4] = 0.0f;
    mout[5] = f;
    mout[6] = 0.0f;
    mout[7] = 0.0f;

    mout[8] = 0.0f;
    mout[9] = 0.0f;
    mout[10] = (zFar+zNear) / (zNear-zFar);
    mout[11] = -1.0f;

    mout[12] = 0.0f;
    mout[13] = 0.0f;
    mout[14] = 2 * zFar * zNear /  (zNear-zFar);
    mout[15] = 0.0f;

```

And after doing `proj * view * model`, I feed it into the shader with `glUniformMatrix4fv()`.

In my shader, I post-multiply the position, like so:

```
gl_Position = modelcamviewprojmat * position;

```

My matrix class has translation in \[12\], \[13\], \[14\]

The things I would try:

1. Switch multiplication order, to see if it helps: sometimes it is model * view * proj, sometimes it is proj * view * model.
2. Make sure the layout of your proj matrix, above, is correct.
> 2 votes

---
Tags: opengl, c++, mathematics
---