# Question
Title: How to pan a perspective camera over a 2D scene with click & drag
I have an issue panning, my camera with the mouse. The camera travels on x and y. I'm using z to zoom. The camera travels over a single textured quad.

I have the camera set up with a View(LookAtLH) and Projection (FOVLH) Matrix. I have the eye (Camera Position), lookAt is mirror of eye on 0 Z and Up (Y) (0, 1, 0);

Until recently I've been using the same method as my keyboard input to pan the mouse. This worked but was inaccurate. I have been given a new requirement to have the image and mouse cursor remain in sync. Meaning have the same point stay under the cursor.

Can someone please help me with the proper conversions from 2D to 3D? I have normalized the 2D mouse to -1 to 1 on both x and y. However, I cannot get the translation scaling correctly and the image runs away the further from center you get. Can someone please walk me through this in detail?

I am working in C# and SharpDX. I've included the Camera class below.

```
public class Camera : ICamera
{
    /// <summary>
    ///
    /// </summary>
    public enum Plane
    {
        None,
        Far,
        Near
    }

    #region Methods

    #region Constructor

    /// <summary>
    ///
    /// </summary>
    /// <param name="viewportSize"></param>
    public Camera(Size viewportSize)
    {
        ViewportSize = viewportSize;
        DefaultZoom = m_Zoom = -5f;

        DefaultPosition = m_Position = new Vector2(0, 0);
        DefaultUp = m_Up = Vector3.Up;

        UpdateView();

        DefaultFieldOfView = m_FieldOfView = (float)Math.PI / 4;
        DefaultAspectRatio = m_AspectRatio = m_ViewportSize.Width.ToFloat() / ViewportSize.Height.ToFloat();
        DefaultNearPlane = m_NearPlane = 0.05f;
        DefaultFarPlane = m_FarPlane = 100f;

        UpdateProjection();
    }

    #endregion

    /// <summary>
    ///
    /// </summary>
    private void UpdateView()
    {
        View = Matrix.LookAtLH(new Vector3(m_Position, m_Zoom), new Vector3(m_Position, 0), m_Up);
    }

    /// <summary>
    ///
    /// </summary>
    private void UpdateProjection()
    {
       Projection = Matrix.PerspectiveFovLH(m_FieldOfView, m_AspectRatio, m_NearPlane, m_FarPlane);
    }

    /// <summary>
    ///
    /// </summary>
    public void Resrt()
    {
        //Reset View
        m_Zoom = DefaultZoom;
        m_Position = DefaultPosition;
        m_Up = DefaultUp;

        UpdateView();

        //Reset Projection
        m_FieldOfView = DefaultFieldOfView;
        m_AspectRatio = DefaultAspectRatio;
        m_NearPlane = DefaultNearPlane;
        m_FarPlane = DefaultFarPlane;

        UpdateProjection();
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="mousePosition"></param>
    /// <param name="viewportSize"></param>
    /// <returns></returns>
    public Vector2 NormalizeMousePosition(System.Windows.Point mousePosition, Size viewportSize)
    {
        var nX= (float)((2.0 * ((float)mousePosition.X) / (float)viewportSize.Width) - 1.0f);
        var nY = (float)((2.0 * (((float)mousePosition.Y) / (float)viewportSize.Height)) - 1.0f) * -1.0f;

        return new Vector2(nX, nY);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="normalizedMousePosition"></param>
    /// <param name="plane"></param>
    /// <returns></returns>
    public Vector3 GetMouseOnPlane(Vector2 normalizedMousePosition, Plane plane)
    {
        var mouseVector = new Vector3(normalizedMousePosition.X, normalizedMousePosition.Y, plane == Plane.Near ? 0.0f : 1.0f);

        return  Vector3.TransformCoordinate(mouseVector, m_View * Projection);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="mousePosition"></param>
    /// <param name="viewportSize"></param>
    /// <param name="plane"></param>
    /// <returns></returns>
    public Vector3 GetMouseOnPlane(System.Windows.Point mousePosition, Size viewportSize, Plane plane)
    {
        var normalizedMousePosition = NormalizeMousePosition(mousePosition, viewportSize);

        return GetMouseOnPlane(normalizedMousePosition, plane);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="mousePosition"></param>
    /// <param name="lastMousePosition"></param>
    public void Pan(System.Windows.Point mousePosition, System.Windows.Point lastMousePosition)
    {
        var origin = NormalizeMousePosition(lastMousePosition, ViewportSize);
        var move = NormalizeMousePosition(mousePosition, ViewportSize);
        var delta = origin - move;

        // Need help here...
        //I need to pan while keeping the same point under the cursor.

    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="mousePosition"></param>
    /// <param name="degrees"></param>
    public void Rotate(System.Windows.Point mousePosition, float degrees)
    {
        var origin = NormalizeMousePosition(mousePosition, ViewportSize);

        // Need help here...
        //I need to rotate on a point of given x, y while looking straight down the z axis.

    }

    #endregion

    #region Properties

    private Vector2 DefaultPosition { get; }

    private Vector2 m_Position;
    public Vector2 Position
    {
        get { return m_Position; }
        set
        {
            if (m_Position == value) return;
            m_Position = value;
            UpdateView();
        }
    }

    private float DefaultZoom { get; }

    private float m_Zoom;

    public float Zoom
    {
        get { return m_Zoom; }
        set
        {
            if(m_Zoom.WithinTolerance(value)) return;
            m_Zoom = value;
            UpdateView();
        }
    }

    //Locked to Camera on Z axis
    //private Vector3 DefaultTarget { get; set; }

    //private Vector3 m_Target;
    //public Vector3 Target
    //{
    //    get { return m_Target; }
    //    set
    //    {
    //        if (m_Target == value) return;
    //        m_Target = value;
    //        UpdateView();
    //    }
    //}

    private Vector3 DefaultUp { get; set; }

    private Vector3 m_Up;
    public Vector3 Up
    {
        get { return m_Up; }
        set
        {
            if (m_Up == value) return;
            m_Up = value;
            UpdateView();
        }
    }

    private Matrix m_View;
    public Matrix View
    {
        get { return m_View; }
        set
        {
            m_View = value;
            m_CameraView = Matrix.Invert(m_View);
        }
    }

    private Matrix m_CameraView;
    public Matrix CameraView
    {
        get { return m_CameraView; }
        set
        {
            m_CameraView = value;
            m_View = Matrix.Invert(m_CameraView);
        }
    }

   public Matrix Projection { get; set; }

    public float DefaultFieldOfView { get; set; }

    private float m_FieldOfView;
    public float FieldOfView
    {
        get { return m_FieldOfView; }
        set
        {
            if (m_FieldOfView.WithinTolerance(value)) return;
            m_FieldOfView = value;
            UpdateProjection();
        }
    }

    public float DefaultAspectRatio { get; set; }

    private float m_AspectRatio;
    public float AspectRatio
    {
        get { return m_AspectRatio; }
        set
        {
            if (m_AspectRatio.WithinTolerance(value)) return;
            m_AspectRatio = value;
            UpdateProjection();
        }
    }

    private float DefaultNearPlane { get; set; }

    private float m_NearPlane;
    public float NearPlane
    {
        get { return m_NearPlane; }
        set
        {
            if (m_NearPlane.WithinTolerance(value)) return;
            m_NearPlane = value;
            UpdateProjection();
        }
    }

    private float DefaultFarPlane { get; set; }

    private float m_FarPlane;
    public float FarPlane
    {
        get { return m_FarPlane; }
        set
        {
            if (m_FarPlane.WithinTolerance(value)) return;
            m_FarPlane = value;
            UpdateProjection();
        }
    }

    private Size m_ViewportSize;
    public Size ViewportSize
    {
        get { return m_ViewportSize; }
        set
        {
            if (m_ViewportSize == value) return;
            m_ViewportSize = value;
            UpdateProjection();
        }
    }

    #endregion
}

 public void Pan(Vector3 normalizedMousePosition, Vector3 normalizedLastMousePosition)
    {
        //var normalizedLastMousePosition = NormalizeMousePosition(lastMousePosition, ViewportSize);
        //var normalizedMousePosition = NormalizeMousePosition(mousePosition, ViewportSize);
        //var delta = origin - move;

        // Need help here...
        //I need to pan while keeping the same point under the cursor.

        var verticalSpan = (float)Math.Tan(0.5f * FieldOfView.ToDegrees() * Math.PI /180f );

        var viewCursor = new Vector3(normalizedMousePosition.X * verticalSpan * (float)(ViewportSize.Width / ViewportSize.Height), normalizedMousePosition.Y * verticalSpan, 1.0f);

        var depth = 0 - Zoom;

        var worldCursor = new Vector3(Position, Zoom) + viewCursor * depth;

        var screenTravel = normalizedMousePosition - normalizedLastMousePosition;

        var worldTravel = new Vector3(screenTravel.X * depth * verticalSpan * (float)(ViewportSize.Width / ViewportSize.Height), screenTravel.Y * depth * verticalSpan, 0f);

        Position += (Vector2)(new Vector3(Position, Zoom) + worldTravel);

    }

```

# Answer
Let's start with your cursor position as a 2D vector, where (-1, -1) is the bottom-left corner of the screen and (1, 1) is the top-right (flip signs accordingly from here on in if you're using different conventions).

We'll convert this to a vector in the camera's view space:

```
 // For a perspective camera with a symmetric frustum,
 // and Field of View measured in degrees from bottom to top:
 verticalSpan = tan(0.5f * fov * pi/180.0)

 viewCursor.x = normalizedScreenCursor.x * verticalSpan * screen.width/screen.height
 viewCursor.y = normalizedScreenCursor.y * verticalSpan
 viewCursor.z = 1.0

```

To extend this to meet your content quad, we need to know its depth along the cameras's forward axis:

```
depth = content.position.z - camera.position.z

```

Then we can convert your cursor position to a world space point on your content plane like so:

```
worldCursor = camera.position + viewCursor * depth

```

Moving your camera as you drag uses the same scaling, just negated (when we move the cursor left, we want the camera to move right):

```
screenTravel = normalizedScreenCursor - previousNormalizedScreenCursor

worldTravel.x = screenTravel.x * depth * verticalSpan * screen.width/screen.height
worldTravel.y = screenTravel.y * depth * verticalSpan
worldTravel.z = 0.0f

camera.position = camera.position + worldTravel

```
> 1 votes

---
Tags: c#, directx, sharpdx
---


title: OpenGL object loader

text:
# Question
Title: OpenGL object loader
I'm following a tutorial on Youtube for OpenGL with LWJGL 3 game development by ThinMatrix. Got to loading custom .obj files. I can only run the provided stall and dragon object. Cannot run my own models created with Blender 2.78. Getting this error:

```
java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at tk.kerdo.gfx.OBJLoader.processVertex(OBJLoader.java:97)

```

My .obj loader: https://pastebin.com/zSVDtsRr My .obj file: https://pastebin.com/k5LZFsRN

How can I change my .obj loader engine to work with my current and new models?

Thanks,

Kerdo K.

# Answer
Your obj file doesn't have UV coordinates. Make sure you unwrap your object before you export it (Here's how you do it in blender)
> 0 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: What is the shortcut to rename stuff in Unity on Linux?
I am using Unity on Ubuntu 16.04 and I can't rename objects or assets using the F2 key as I could when I was using Windows.

What is the shortcut on Linux then?

# Answer
> 5 votes
There's a way to just custom make what you need to do. Put the following code inside a script with the same name (doesn't have to be on a game object).

```
using UnityEngine;
using UnityEditor;
using System.Reflection;

public class MenuItemsExample
{
    [MenuItem("Edit/Rename _F2")]
    private static void Rename()
    {
        var type = typeof(EditorWindow).Assembly.GetType("UnityEditor.SceneHierarchyWindow");
        var hierarchyWindow = EditorWindow.GetWindow(type);
        var rename = type.GetMethod("RenameGO", BindingFlags.Instance | BindingFlags.NonPublic);
        rename.Invoke(hierarchyWindow, null);
    }
}

```

This will bind F2 to a rename functionality, using reflection. I've found this from the Unity forums (had to dig a bit but nothing too hard to find). The name part is mine, that's what binds F2 to the function and there's also a nice menu item that appears in your edit menu. Here's a GIF that shows the functionality (shouldn't be dependent on the OS):

Here's the link to the forum post.

---
Tags: unity, linux
---


# Question
Title: How to make a game where match duration is determined only by skill disparity between the best player and the second best player?
I want to create a real-time multiplayer game (with a variable number of players, potentially 2-20+, per match) where the match duration is determined only by how much better the best player is compared to the second best player. Thus, 2 properties are required:

1. Game duration is independent of the number of players. Racing games have this property in that the time it takes for a match to end (which is how long it takes the best player to finish) is independent of how many players are playing. However they don't have the 2nd property.
2. Game duration is inversely proportional to the skill disparity between the best and second best players - we want close games to last longer than complete stomps. I'm not aware of any game where there is such a strong correlation between match duration and skill disparity that one could say it's the rule. I mean, in Chess, if one is really bad, one could be mated in a few moves, and if two players are close in skill, then games might last really long, but this is not certain. In any case, these games tend to not have the first property.

How might one design a game that has both properties?

# Answer
Im not quite sure if this example really fits your two requirements, but Micro Machine games have an elimination mode that basically does that.

1. The Game duration is idependent of the number of players, as its only important, when the second best player gets eliminated.
2. Game duration is inversely proportional to the skill disparity between the best and second best players - the better the best player, the sooner everyone else gets eliminated.

Only problem would be, that you could argue at 1. that more players could interact more and thus disturb the other players, like the first and the second best player. The alternative would be to disable player interaction at all.
> 1 votes

# Answer
Here's a solution I thought up (but consider to be imperfect):

Racing game except when the top player pulls ahead of the second player by a certain distance, the race ends instantly. This way, if two players are roughly equal in speed, the race can go on really long, but if the top player is much faster than everyone else, then the game ends pretty quickly.

The problem with this game is that there has to be no personalized interaction between players, and if there's no player-player interaction then the game will feel boring.

The problem with having player-player interaction is that the minimal total duration will inherently depend on the number of players (assuming there is a minimal amount of time that a player-player interaction will take and that we want all players to interact with the best player). I suppose one way to minimize the problem here would be to make the interactions really short and repeat them a lot over time (so that the worst players only interact with the best player once each whereas the second best player might interact with the best player hundreds of times). But I'm not sure how such a game might be constructed.
> 0 votes

---
Tags: game-design
---


# Question
Title: Create Script from custom templates issue: They are created with the default name and cannot been named on creation
I was just being introduced to the **AssetDatabase** class, and I was curious of creating Script Templates, such as Interfaces, pure C# classes, and a MonoBehaviour template more suitable for my work style.

I tried to emulate a solution I found on Unity Forums, and the template creation goes well, except that the name gets setted once it is created, and it doesn't let you name the created asset, as the Unity Scripts let you once you create them. The fact that the name is not changed by the user, makes the script on its default state, with the exact code the template has, without changing the #SCRIPTNAME#s declared, throwing errors, and being counterproductive with the time optimization goals I had in mind.

```
using UnityEditor;
using UnityEngine;
using System.IO;

public class CustomScriptsCreator
{
    public const string CONTEXT_MENU_PATH = "Assets/Create/Custom Scripts";     /// <summary>Custom Scripts default Path.</summary>
    public const string CONTEXT_MENU_CUSTOM_C_SHARP = "/C# MonoBehaviour";
    public const string CUSTOM_TEMPLATE_FOLDER_PATH = "Assets/Custom Script Templates";
    public const string CUSTOM_C_SHARP_TEMPLATE_PATH = "C#Script_CustomMonoBehaviourScript.cs.txt";
    public const string PATH_NOT_FOUND_MESSAGE = "Script Template Not Found";
    public const string WINDOW_ERROR_MESSAGE = "There is no Template at path: \n\n";
    public const string WINDOW_OK_ANSWER = "Ok";

[MenuItem(CONTEXT_MENU_PATH + CONTEXT_MENU_CUSTOM_C_SHARP)]
public static void Create(MenuCommand _cmd)
{
    Object selection = Selection.activeObject;

    if (selection != null)
    {
        string path = AssetDatabase.GetAssetPath(selection);

        if (File.Exists(path))
        {
            path = Path.GetDirectoryName(path);
        }
        if (string.IsNullOrEmpty(path))
        {
            path = "Assets/";
        }

        /// THIS WAS JUST A FAILED TEST...
        /*Object obj = Resources.Load("ScriptTemplates/" + CUSTOM_C_SHARP_TEMPLATE_PATH);

        if(obj != null)
        {
            AssetDatabase.CreateAsset(obj, Path.Combine(path, "NewScript.cs"));
        }
        else
        {
            EditorUtility.DisplayDialog
            (
                PATH_NOT_FOUND_MESSAGE,
                WINDOW_ERROR_MESSAGE + (CUSTOM_TEMPLATE_FOLDER_PATH + "/" + CUSTOM_C_SHARP_TEMPLATE_PATH),
                WINDOW_OK_ANSWER
            );
        }*/

        //string newName = EditorUtility.SaveFilePanelInProject("Save Your Prefab", "NewScript.cs", "cs", "Please select file name to save prefab to:");
        //File.Copy((CUSTOM_TEMPLATE_FOLDER_PATH + "/" + CUSTOM_C_SHARP_TEMPLATE_PATH), Path.Combine(path, "NewScript.cs"));
        if(AssetDatabase.CopyAsset((CUSTOM_TEMPLATE_FOLDER_PATH + "/" + CUSTOM_C_SHARP_TEMPLATE_PATH), Path.Combine(path, "NewName.cs")))
        {
            // IT CHANGES THE FILE NAME SUCCESSFULLY, BUT NOT ON THE SCRIPT.
            //AssetDatabase.RenameAsset(Path.Combine(path, "NewName.cs"), "KillMePlease.cs");

            AssetDatabase.Refresh();
        }
        else
        {
            EditorUtility.DisplayDialog
            (
                PATH_NOT_FOUND_MESSAGE,
                WINDOW_ERROR_MESSAGE + ((CUSTOM_TEMPLATE_FOLDER_PATH + "/" + CUSTOM_C_SHARP_TEMPLATE_PATH)),
                WINDOW_OK_ANSWER
            );
        }
    }

}

```

}

The paths are ok, since the script is being created. If there is more information you need, let me know. Thanks in advance.

# Answer
**In case anyone has, or had the same problem:**

I found a good solution on a GIT repository provided by a guy identified as **Liortal**, with additional extensions I made for more templates creations (interfaces, structs, scriptableobjects, etc.), but **Liorta's** base code was enough to achieve my goals. The use of a **EndNamedEditAction** inhereted class was necessary to handle the name editing (so far I haven't found information about the class, so I lefted it as it was).

These are both scripts used, combined on a single scripts for example purposes:

```
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;
using UnityEngine;

public class CodeTemplateGenerator
{
    /// Inherits from EndNameAction, must override EndNameAction.Action
    public class DoCreateCodeFile : EndNameEditAction
    {
        public override void Action (int instanceId, string pathName, string resourceFile)
        {
            Object o = CodeTemplates.CreateScript(pathName, resourceFile);
            ProjectWindowUtil.ShowCreatedAsset (o);
        }
    }

private const string MENU_ITEM_PATH = "Assets/Create Template";     ///< <summary>Menu Item's path.</summary>
private const string CLASS = "C# Class";                            ///< <summary>Class's path [must be combined with menu item's path].</summary>
private const string INTERFACE = "Interface";                       ///< <summary>Interface's path [must be combined with menu item's path].</summary>
private const string REPLACABLE_NAME_TAG = "##NAME##";              ///< <summary>NAME's replacement tag.</summary>
private const string REPLACABLE_TABSPACE_TAG = "##TABSPACE##";      ///< <summary>TABSPACE's replacement tag.</summary>

/// <summary>C#'s Script Icon [The one MonoBhevaiour Scripts have].</summary>
private static Texture2D scriptIcon = (EditorGUIUtility.IconContent ("cs Script Icon").image as Texture2D);

/// <summary>Creates a new C# Class.</summary>
[MenuItem(MENU_ITEM_PATH + CLASS)]
private static void CreateClass()
{
    CodeTemplates.CreateFromTemplate
    (
        "NewClass.cs",                                              // Class's temporal name.
        @"Assets/CodeTemplates/Editor/Templates/ClassTemplate.txt"  // Template's path.
    );
}

/// <summary>Creates a new C# interface.</summary>
[MenuItem(MENU_ITEM_PATH + "C# Interface", false, MENU_ITEM_PRIORITY)]
private static void CreateInterface()
{
    CodeTemplates.CreateFromTemplate
    (
        "NewInterface.cs",
        @"Assets/CodeTemplates/Editor/Templates/InterfaceTemplate.txt"
    );
}

/// <summary>Creates Script from Template's path.</summary>
internal static UnityEngine.Object CreateScript(string pathName, string templatePath)
{
    /// Subtract spaces [" "].
    string className = NormalizeClassName(Path.GetFileNameWithoutExtension(pathName));
    string templateText = string.Empty;

    UTF8Encoding encoding = new UTF8Encoding (true, false);

    if (File.Exists(templatePath))
    {
        /// Read procedures.
        StreamReader reader = new StreamReader(templatePath);
        reader.ReadToEnd();
        reader.Close();

        templateText = templateText.Replace(REPLACABLE_NAME_TAG, className);
        templateText = templateText.Replace(REPLACABLE_TABSPACE_TAG, string.Empty);
        /// You can replace as many tags you make on your templates, just repeat Replace function
        /// e.g.:
        /// templateText = templateText.Replace("#NEWTAG#", "MyText");

        /// Write procedures.
        StreamWriter writer = new StreamWriter(Path.GetFullPath(pathName), false, encoding);
        writer.Write (templateText);
        writer.Close();

        AssetDatabase.ImportAsset(pathName);
        return AssetDatabase.LoadAssetAtPath (pathName, typeof(Object));
    }
    else
    {
        Debug.LogError(string.Format("The template file was not found: {0}", templatePath));
        return null;
    }
}

/// <summary>Creates a new code file from a template file.</summary>
/// <param name="initialName">The initial name to give the file in the UI</param>
/// <param name="templatePath">The full path of the template file to use</param>
public static void CreateFromTemplate(string initialName, string templatePath)
{
    ProjectWindowUtil.StartNameEditingIfProjectWindowExists
    (
        0,
        ScriptableObject.CreateInstance<DoCreateCodeFile>(),
        initialName,
        scriptIcon,
        templatePath
    );
}

/// <summary>Subtracts white spaces [" "] for Class's name.</summary>
private static string NormalizeClassName(string fileName)
{
    return fileName.Replace(" ", string.Empty);
}

```

}

To create templates, remember to have them stored like **"MYTEMPLATE.cs.txt"** and consider using this kind of format, with replacement tags:

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

[CreateAssetMenu]
public class ##NAME## : ScriptableObject
{
    ##TABSPACE##
}

```
> 1 votes

---
Tags: unity, c#, editors, asset-creation
---


# Question
Title: Display image a couple seconds after an enemy spawns?
So right now I have enemies that spawn behind objects with a delay.

What I need is to display an image on the screen 5 seconds after each enemy spawns (it's to show the player it has been "attacked") and that image has to disappear after like 2 seconds so.

I know I have to use `WaitForSeconds` but I don't know how because everything I've tried isn't working.

Here's my code:

```
 public class TimedSpawn : MonoBehaviour {

     public GameObject spawnee;
     public bool stopSpawning;
     public float spawnTime;
     public float spawnDelay;

     // Use this for initialization
     void Start () {
         InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
     }

     public void SpawnObject (){
         Instantiate (spawnee, transform.position, transform.rotation);

         if (stopSpawning) {
             CancelInvoke ("SpawnObject");
         }
     }
 }

```

# Answer
Well, all those co-routines and waiting for some seconds are nice but, why not just use `Invoke()` for this purpose as well?

```
//...
public void SpawnObject (){
    var warningDelay = 5.0;
    Instantiate (spawnee, transform.position, transform.rotation);
    Invoke("CreateWarningImage", warningDelay);
    if (stopSpawning) {
        CancelInvoke ("SpawnObject");
    }

}
//someTransform is where you want the image to be, assuming you've already defined it
public void CreateWarningImage(){
    Instantiate (warning, someTransform.position, someTransform.rotation);
}

```

And then, you just put a destroy on the a script's `Awake()` function which is on the image like so:

```
var lifetime = 2.0;
function Awake()
{
    Destroy(gameObject, lifetime);
}

```

Note that I'm assuming you're not spawning hundred thousand enemies per second, so the performance difference between an invoke call (looks for a string) and a co-routine shouldn't matter at all. For the simplest stuff (like doing one thing after some seconds), you shouldn't really need anything other than `Invoke()`.
> 1 votes

# Answer
Use a co routine to accomplish this. I don't know how you want to display the image, but for this example I will use the Unity UI Image. Example below:

```
public class Example : MonoBehaviour {

public GameObject spawnee;
public bool stopSpawning;
public Image image;

public float spawnTime;
public float spawnDelay;

// Use this for initialization
void Start()
{
    image.gameObject.SetActive(false);
    InvokeRepeating("SpawnObject", spawnTime, spawnDelay);
}

public void SpawnObject()
{
    Instantiate(spawnee, transform.position, transform.rotation);
    StartCoroutine(DisplayMessage(5, 2, image));

    if (stopSpawning)
    {
        CancelInvoke("SpawnObject");
    }
}

public IEnumerator DisplayMessage(float displayOffset, float displayDuration, Image im)
{
    float time = 0f;
    do
    {
        time += Time.deltaTime;
        yield return null;
    }
    while (time < displayOffset);

    im.gameObject.SetActive(true);

    float time2 = 0f;
    do
    {
        time2 += Time.deltaTime;
        yield return null;
    }
    while (time2 < displayDuration);
    im.gameObject.SetActive(false);
}
}

```

Hope this helps.
> 0 votes

---
Tags: unity, image, spawning
---


title: Guide for beginner in shaders

text:
# Question
Title: Guide for beginner in shaders
first of all i know nothing about opengl or shaders and now tried to learn but im stuck little bit, I've downloaded some shader tutorials from unity learning center but i can't completely understand what is happening in the codes i know C++ and C# learnt the syntax of shaderlabs but still i cant really understand what is happening in codes and i can't write something that is in my mind i can only write the things that someone taught me and even i don't know why but shading section in unity documentation is little hard to understand for me so i've been researching recently and found GLSL ,

now i have some questions:

1: Do i have to learn opengl or DirectX for better understanding and writing shaders in unity or even UDK?

2: if its not important to learn opengl should i learn GLSL?

3: overall im little confused about shaders they say unity shaderlabs is based on CGFX from nvidia should i learn this one?

if you give me a good guide for shaders i will be grateful i just dont know where to start,
Note: i cant really buy a E-Book or something its not available here so i have to use free ones.

# Answer
> 1 votes
It really depends on why you want to learn about shaders.

* Are you going to use Unity? Then learn Unity's system.
* If you want to learn to use OpenGL, then learn about GLSL.

If you are confused about shaders in general, try to learn more about the graphics pipeline and how shaders fit into it.

This could be useful if you are going to use OpenGL:

---
Tags: unity, opengl, shaders, directx
---


# Question
Title: ECS: is it beneficial to manage the data organisation of components before updating a system?
When I process a bunch of component data, I'd like that data to be sorted in such a way that I can iterate through the component buffers linearly. For instance when I want to update the physics system, in an ideal world the buffers for the TransformComponent, MovementComponent and PhysicsBodyComponent are structured in such a way that I would be able to iterate over the entities like this:

```
for(int i = 0; i < m_numEntitiesInSystem; i++)
{
    Transform& transform = g_transformBuffer[i];
    MovementComponent& movement = g_movementBuffer[i];
    PhysicsBodyComponent& body = g_physicsBodyBuffer[i];
    // ... update physics ...
}

```

The main advantage of this is that I would have next to no cache misses for this system. Because different systems require different (combinations of) components, this would imply that before every system update, I would either have to sort the respective component buffers so that they are aligned or I would have to use a cache that is local to the system only (this cache would need to be synced every time a component changes).

Of course both approaches come at a cost as well, sorting the component buffers could affect the ability to execute systems on separate threads. Not to mention that the sorting process itself might have its own performance drawbacks. Syncing the component data implies that some components might need to be copied over possibly several times per frame which again might come with its own performance drawbacks.

My question is: is the price of sorting or syncing worth being able to process data linearly? Or is it wiser to try organise the data in such a way that the most executed/expensive systems perform optimally and others potentially less so. If the former, would it be preferable to use the sorting method or the syncing method?

Also please don't tell me that "premature optimization is evil". Since this is more or less the foundation of my engine, I want it to be as well written and designed as I can. Or at least I want to understand the consequences of picking one method over the other.

Thank you so much!

# Answer
> 1 votes
It's difficult to say which way is best, since we don't know how prone your setup is to cache misses without this.

I think I remember Jonathan Blow describing doing this type of sort-before-update on one of his developer streams, as a way to improve performance late in a project, so there certainly could be cases where it's beneficial. Without profiling data though, it's not clear how much net savings you'd get, and whether it's worth the cost in complexity or threading flexibility as you mentioned.

One thing to consider is that just iterating in a sorted order, even with gaps, can still be a lot better than a random zig-zag backwards and forwards through memory!

So you might not need to re-sort for every system to get the lion's share of the cache miss savings. A single shared sort order that tends to keep clusters of entities close together for one or a few of your highest-throughput systems might be enough to keep your game running smoothly, even if most / all systems still encounter some gaps in their iteration.

But again, we can't really quantify this to test it without knowing the typical distributions of your data at runtime. There are use patterns under which this will perform at efficiency approaching the theoretical maximum, and other use patterns under which it will suffer as badly as pointer-chasing. So there's really no substitute for building tests and profiling, even if it means you go down the wrong road at first and need to refactor once you know in detail what your runtime data characteristics are like.

# Answer
> 1 votes
It's great that you have taken the time to think about a couple of ways to accomplish this.

Unfortunately, there is no way to tell what's the best approach before you try it with actual data in an actual game.

Guessing where the bottlenecks are and trying to optimize that in advance may lead to work done in vain.

I spent two weeks rehashing the structure of some data over which were were doing a lot of process. All the data was created in random memory location, using pointers. There was *a lot* on cache misses.

My assumption was that by regrouping the data in arrays, and having it accessed sequentially would reduce the cache misses and thus the time it takes to perform the calculation.

The results of all of this? It reduced the cache misses *a lot*, there was a 10% gain in performance for the processing itself, but the simple work to reorganize the data simply killed the performance gained.

So my suggestion is this: Build both approaches in your engine. Give tools to your user to measure how long a process takes with their real-world situation and allow them to use the one they feel is the best for them in their situation.

---
Tags: c++, performance, data-oriented
---


# Question
Title: How can i rotate the FPSController to it's original rotation angle?
It should be kind of slowly standing effect. The FPSController is starting at rotation: X = 7 Y = 112 Z = -31

The problem is that i have on the FPSController a script that i use the mouse to rotate the camera around. And i see that when i rotate the camera the center point of the FPSController seems stuck on this angle even if i change the rotation to 0,0,0

If i start the game running it when the rotation of the FPSController is 0,0,0 then it's standing but when i start the game with 7,112,-31 and then moving the mouse it keep be locked on this rotation values. And i want it to slowly return to the original 0,0,0

I tried when the game is running and the fpscontroller rotation set to 7,112,-31 to change it to 0,0,0 but it keep staying at the rotation of 7,112,-31

What i want is that the fpcscontroller to stand. I don't think that i need to change it's position but only the rotation.

In my script i tried this: At the top:

```
public FirstPersonController fpc;
public float speed = 10F;

```

Then in the Update:

```
void Update()
{
  fpc.transform.rotation = Quaternion.Slerp(fpc.transform.rotation,
  Quaternion.Euler(0, 0, 0), Time.deltaTime * speed);
}

```

But it didn't return it to the standing position it keep it on the current rotation 7,112,-31

# Answer
> 2 votes
I think I didn't get quite right your issue, but I'll try...Maybe you could store the initial rotation on **Awake:**

**Edit:** Now I got your issue. You are using the interpolation (Slerp) wrong. It is based on the formula:

> **P = P0 + (t * (P1 - P0)), 0 \< t \< 1**

So it is an interpolation normalized between 0 and 1, the problem with your function is that **(Time.deltaTime * speed)** is always giving a delta of frames duration (usually 0.02) multiplied by your speed, that is never going to reach 1 to have your rotation at the Quaternion.identity. You should play with a float that each frame gets summed until it reaches 1, giving a quick example:

```
Quaternion initialRotation; /// <summary>Here you store the initial rotation.</summary>
float t = 0.0f; /// <summary>Time reference for the interpolation.</summary>

/// <summary>Called on MonoBehaviour initialization.</summary>
void Awake()
{
    initialRotation = transform.rotation;
}

/// <summary>This MonoBehaviour's Tick at each frame.</summary>
void Update()
{
    transform.rotation = Quaternion.Slerp(initialRotation, Quaternion.identity, t);
    t += (Time.deltaTime * speed);
}

```

So you could use that value initialized on Awake, the slerp takes that rotation, since interpolating between the actual rotation wouldn't give the expected results. We are using **Quaternions** here, since what there is shown on the inspector is an Euler Angle representation of the quaternion, and its less recomended to play with **eulerAngles**. So, if you want your FPC to be at a (0,0,0) rotation, then set its transform.rotation to **Quaternion.identity**.

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


# Question
Title: Libgdx - notification popup (something like Toast) - on both Desktop and Android
I'm trying to implement a notification system with LibGDX. As we know, Android has it's Toast which is great, but I can't use it in Desktop mode.

I tried extending Dialog etc, adding as an actor and it all worked, but there's one problem - it still needs to be within the 'stage' object range, cause I have to add the 'notification actor' to the stage.

Do you have any ideas how to implement it in a static way, that the notification dialog/label/window would be 'callable' from the whole app?

Here's my code:

```
public class Notification extends Dialog {

public enum NotificationType{
    SUCCESS, FAIL, INFO;
}

static Skin skin = new Skin(Gdx.files.internal("data/notificationskin.json"));
Label label;
public Notification(String text, NotificationType type) {
    super("", skin);
    setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()/10);
    setPosition(0, Gdx.graphics.getHeight() + getHeight());
    label = new Label(text, skin);
    add(label).center();

    label.setColor(Color.BLUE);
    setKeepWithinStage(false);
    show();
}

public void show(){

    MoveToAction moveTo = new MoveToAction();
    moveTo.setPosition(getX(), Gdx.graphics.getHeight() - getHeight());
    moveTo.setDuration(2f);

    MoveToAction moveBack = new MoveToAction();
    moveBack.setPosition(getX(), Gdx.graphics.getHeight() + getHeight());
    moveBack.setDuration(2f);

    SequenceAction action = new SequenceAction(moveTo, Actions.delay(1.0f), moveBack, Actions.removeActor());
    addAction(action);

}
}

```

To show the toast I need to call:

```
Notification not = new Notification("You're now connected", SUCCESS);
stage.addActor(not);

```

which is bad - it should be static.

# Answer
> 3 votes
I have implemented Android-like toast for my project and decided to share it with you! Enjoy: Toast LibGDX (GitHub).

Easy to use:

1. Include Toast in your LibGDX project
2. Create ToastFactory for your toasts (using Builder):

```
Toast.ToastFactory toastFactory = new Toast.ToastFactory.Builder()
        .font(font)
        .build();

```
3. Create toast: `Toast toast = toastFactory.create("Hello world!", Toast.Length.LONG);`
4. Display it in `render()`: `toast.render(Gdx.graphics.getDeltaTime());`

# Answer
> 0 votes
In your notification class, you use Actions which you can't have if Notification does not inherit from actor class (so you would have to recode those animations by hand). Actors can be drawn like that :

```
// Will call actor.draw(SpriteBatch batch)
stage.addActor(actor)

```

Or

```
actor.draw(batch)

```

In both case, you **need a SpriteBatch** to draw something. So you can't draw anything if you have no SpriteBatch, stage provide you one, but you can also have a SpriteBatch dissociated from stage.

In my opinion, you should go the way you do. I agree it looks less beautiful than Toast, but doing something like Toast that can interact with your display without using SpriteBatch will took to much time for doing what you can already do :).

But if you really want to do it that way, you should take a look at Views. For example, Google Play Leaderboards display a view above your stage, so i suppose you can display a view with your toast above your stage too.

Hope this will help !

---
Tags: libgdx, ui-design
---


title: Lerp rotation is offset

text:
# Question
Title: Lerp rotation is offset
I am trying to get an object to slowly look at another object, that is, rotate slowly so its forward points towards the target position. Here is my code:

```
using UnityEngine;

public class LookAtTheDamnThing: MonoBehaviour
{
    public Transform target;
    public float speed;

    void FixedUpdate()
    {
        AimAtTarget();
    }

    public void AimAtTarget()
    {
        Vector3 direction = target.position - transform.position;
        Quaternion toRotation = Quaternion.FromToRotation(transform.forward, direction);
        transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed * Time.time);
        Vector3 fwd = this.transform.TransformDirection(Vector3.forward);
        Debug.DrawRay(this.transform.position, fwd * 50, Color.green);
    }
}

```

This results in the object looking kind of towards the target but never actually looking at it. I cannot for the life of me see my mistake. Can anyone help me?

# Answer
> 1 votes
There are a few different issues here.

First, you're constructing `toRotation` as a relative rotation (some amount of *change* in rotation)

```
Quaternion toRotation = Quaternion.FromToRotation(transform.forward, direction);

```

But then you're applying `toRotation` as a destination (a final rotation to ease toward)

```
transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed * Time.time);

```

Imagine if we did this with position, starting with an object at `x=8` that wants to move to `x=10`. The change in `x` is +2, but if we lerp toward that change value like so:

```
 Mathf.Lerp(startPosition, endPosition - startPosition, weight)

```

...then as the interpolation weight gets closer to 1, our `x` gets closer to 2 - not to 10 where we want it to be!

(When applied in a compounding way frame over frame, this will seek out an equilibrium point where `x = lerp(x, 10 - x, weight)`, `x = (1 - weight) * x + weight * 10 - weight * x`, `2 weight * x = weight * 10`, `2 x = 10`, `x = 5`... still not where we wanted it to be!)

So, first we need to describe the destination orientation we want to have. It looks like you probably want something like this:

```
// Calculate direction as before.
Vector3 direction = target.position - transform.position;

// Use LookRotation to form a rotation that looks along that vector.
// (You can optionally pass a second vector as "up" to control the twist).
Quaternion toRotation = Quaternion.LookRotation(direction);

```

Then, if you want to rotate toward this location at a constant rate, as John Hamilton says, you can use the Quaternion.RotateTowards method:

```
float step = speed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, step);

```

Or, if you want the aim to be faster the further off-target it is, and gradually ease-in as it locks on, you can keep the exponential ease you were using before, but with the destination as calculated above, and correcting the time adjustment like so:

```
// Here "speed" is replaced by "sharpness," a parameter between 0 & 1
// that controls how smooth vs fast the aim is.
// referenceFramerate is a constant like, say, 30.0f. It adjusts the
// "units" of sharpness to be the same as you'd use at that framerate
blend = 1f - Mathf.Pow(1f - sharpness, Time.deltaTime * referenceFramerate);

transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, blend);

```

# Answer
> 0 votes
Any of the Lerp (linear interpolation) functions (Mathf, Vector3, Quaternion \[ok, maybe quaternions don't apply since it's a matrix\], etc.) works following this formula: **P = P0 + (t * (P1 - P0)), 0 \< t \< 1**, where, as the formula suggests, t which is time goes between 0 and 1. So what this function gives you is a point of a delta between two points multiplied by a normalized time.

What I do is to use coroutines to handle such interpolations, but since you are using an update, maybe you could try with **Quaternion.LookRotation(Vector3 \_direction)**, instead of using **Quaternion.FromToRotation**.

As a side node, you could use transform.forward, instead of using **TransformDirection(Vector3 \_normal)**. Transform.forward, transform.up and transform.right gives you already TransformDirection with (0,0,1), (0,1,0) & (1,0,0) respectively.

# Answer
> 0 votes
There's already a Unity built-in doing what you need to do. You shouldn't need to re-invent the wheel, unless you want it to do very specific things other than just rotating towards another game object. Example from the link:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Transform target;
    public float speed;
    void Update() {
        float step = speed * Time.deltaTime;
        transform.rotation = Quaternion.RotateTowards(transform.rotation, target.rotation, step);
    }
}

```

Also, I suggest using `Update()` instead of `FixedUpdate()` for this kind of movement (well, Unity examples also seem to suggest that), since the time-step is usually faster in the `Update()` function, you should get a smoother movement overall.

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


title: Unity3d - Attach to Unity not working

text:
# Question
Title: Unity3d - Attach to Unity not working
I need to debug my scripts, but if I click "Attach to Unity" or "Attach to Unity and Play" then the button is just grayed out and after a few seconds it is clickable again, but nothing happens.

I already tried to restart visual studio, but it did not helped.

I restarted unity, but this brings no success too.

# Answer
> 0 votes
Today everything just works fine. Thats so weird. Yesterday I had no chance but today everything is perfectly fine. What is the reason? Next time whenever I have a problem with software, I will just turn my computer off for some minutes and then turn it on again, sounds stupid? I know, but apparently it works.

# Answer
> 3 votes
**Answering comments (still can't comment):**

I only had to do it for one script.

If that didn't work, you can try "Assets -\> Reimport All", since it's supposed to fix corruptions in your project. Notice Unity warning saying it can that several hours.

**Original answer:**

I had a similar problem this morning, found a lot of solutions, but the only one that worked for me was to click on the file, go to "Debug-\> (Project) Properties \> Compile Action", select "None" and then select "Compile" again.

That seems like a bug but a have no ideia why that worked.

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


title: Best way to call LibGDX modules?

text:
# Question
Title: Best way to call LibGDX modules?
It has been mentioned in the "Application Framework" section of the LibGDX online wiki that accessing the 6 modules (application, audio, files, graphics, input & net) in a static way is not the best practice.

The exact wording written int the wiki is below:

> The modules described earlier can be accessed via static fields of the Gdx class. This is essentially a set of global variables that allows easy access to any module of libgdx. While generally viewed as very bad coding practice, we decided on using this mechanism to ease the pain usually associated with passing around references to things that are used often in all kinds of places within the code base.

But almost all LibGDX applications that I have seen, modules information is fetched in a static way. If static way is not the right way then how to access these modules?

# Answer
My reading of the passage you quoted is that it's not telling you, as a user, "Don't use these static fields we gave you. That would be bad coding practice on your part" (Well then why did the creators expose them? Meanies!)

Rather, it's saying "As a general rule, exposing these static fields is bad coding practice *on our part*, but we consider it to be a worthwhile trade-off to make it easier for you"

So, there's no particular prohibition on using these modules via their static fields. Since they were designed to be accessed that way, and the creators were apparently conscious of the ramifications of this choice, you're unlikely to create trouble for yourself by going with the flow they created. (And in any case, you can't stuff that genie back in the bottle - they remain globally accessible, with all that comes with that, even if you try to maintain your own more controlled method of accessing them)

---

In your own code, creating your own new global variables this way can open the door to bugs. Once something is global, it's hard to track down where any particular change to it came from, and it's easy for unrelated parts of your code (or libraries you're using) to do contradictory things with it, unknowingly interfering with each other.

It can also make the code hard to scale: if in the future you need multiple instances of something you used to access via a global variable, or multiple flavours of it, now you need to refactor a lot of code to select the right one.

For these reasons, a number of other patterns are often recommended for handling these kinds of dependencies, such as dependency injection or service locators.

But again, you don't have to worry about that for the built-in modules that are already exposed via static fields. The creators of those modules already weighed these alternatives and decided global access was safe enough and worthwhile for this case, and as you noted, a lot of software uses them this way without issues.
> 3 votes

---
Tags: libgdx
---


# Question
Title: How to convert this physics2d raycast with ^ code to physics raycast
While searching on the net I encountered a piece of code in a tutorial I want to use in my game but don't know how to convert it to physics.raycast (https://www.youtube.com/watch?v=1i1hTLU6JTY)

it's about the following piece of code I want to convert:

```
RaycastHit2D maxSlopeHitLeft = Physics2D.Raycast (raycastOrigins.bottomLeft, Vector2.down, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask);
RaycastHit2D maxSlopeHitRight = Physics2D.Raycast (raycastOrigins.bottomRight, Vector2.down, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask);
if (maxSlopeHitLeft ^ maxSlopeHitRight) {
 SlideDownMaxSlope (maxSlopeHitLeft, ref moveAmount);
 SlideDownMaxSlope (maxSlopeHitRight, ref moveAmount);
}
```

I especially don't understand the use of ^, isn't it the same as saying

```
if((!maxSlopeHitLeft && maxSlopeHitRight) || (maxSlopeHitLeft && !maxSlopeHitRight))

```

I hope someone can help me with the 1st piece of code.

I tried to convert the code myself as follow

```
RaycastHit maxSlopeHitLeft, maxSlopeHitRight;
if(Physics.Raycast (raycastOrigins.bottomLeft, Vector2.down, out maxSlopeHitLeft, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask) ^ Physics.Raycast (raycastOrigins.bottomRight, Vector2.down, out maxSlopeHitRight, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask)) {
SlideDownMaxSlope (maxSlopeHitLeft, ref moveAmount);
SlideDownMaxSlope (maxSlopeHitRight, ref moveAmount);
}

```

when my player reaches an edge of a platform it freezes all movement, while in the source tutorial it doesn't

Here is the SlideDownMaxSlope method, it check whether the angle is high enough to slide and calculates the horizontal moving amount

```
void SlideDownMaxSlope(RaycastHit Hit, ref Vector3 MoveAmount){
    float SlopeAngle = Vector3.Angle (Hit.normal, Vector3.up);
    if (SlopeAngle > MaxSlopeAngle) {
        MoveAmount.x = Mathf.Sign (Hit.normal.x) * (Mathf.Abs (MoveAmount.y) - Hit.distance) / Mathf.Tan (SlopeAngle * Mathf.Deg2Rad);

        CI.SlopeAngle = SlopeAngle;
        CI.SlideDownSlope = true;
        CI.SlopeNormal = Hit.normal;
    }
}

```

plus in an update function of another script there is a line for calculating the vertical moving amount

```
if(Grounded) {
    if (PCS.CI.SlideDownSlope) {
        Velocity.y += PCS.CI.SlopeNormal.y * -Gravity * Time.deltaTime;
    } else {
        Velocity.y = 0;
    }
}

```

# Answer
Before adding the line *if(Hit.collider != null) {* player will freeze all movement when reaching an edge. Because there are 2 raycasthit involved in the process of detecting slopes, I added an if statement to filter out the 1 raycast that actually does hit a slope.

```
RaycastHit maxSlopeHitLeft, maxSlopeHitRight;
if(Physics.Raycast (raycastOrigins.bottomLeft, Vector2.down, out maxSlopeHitLeft, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask) ^ Physics.Raycast (raycastOrigins.bottomRight, Vector2.down, out maxSlopeHitRight, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask)) {
SlideDownMaxSlope (maxSlopeHitLeft, ref moveAmount);
SlideDownMaxSlope (maxSlopeHitRight, ref moveAmount);
}

void SlideDownMaxSlope(RaycastHit Hit, ref Vector3 MoveAmount){
    if(Hit.collider != null) {
    float SlopeAngle = Vector3.Angle (Hit.normal, Vector3.up);
        if (SlopeAngle > MaxSlopeAngle) {
            MoveAmount.x = Mathf.Sign (Hit.normal.x) * (Mathf.Abs (MoveAmount.y) - Hit.distance) / Mathf.Tan (SlopeAngle * Mathf.Deg2Rad);

            CI.SlopeAngle = SlopeAngle;
            CI.SlideDownSlope = true;
            CI.SlopeNormal = Hit.normal;
        }
    }
}

```
> 0 votes

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


# Question
Title: Batch conversion of PVR to JPEG (or similar)
The command line PVRTexTool works very well for getting textures into a PVR format, but I need a way of going the opposite directions. Does anyone know of a good command line tool (or GUI with a batch mode) that will convert a PowerVR texture to a more common image format (like JPEG or PNG?)

# Answer
> 3 votes
Inside one of the folders of PVRTexTool you find PVRTexToolCLI.exe, that is the command-line version of it. You can use a batch command on it like this:

```
for %f in (*.pvr) do PVRTexToolCLI.exe -i "%f" -d -f r8g8b8a8

```

# Answer
> 2 votes
I do it in 3 steps:

1. PVRTexToolCLI -dds -fDXT1 -iX.pvr -oX.dds
2. ImageMagick X.dds X.png (or X.jpg)
3. rm X.dds

# Answer
> 1 votes
Check out ImageMagick \- it seems to do everything, and has a good command line interface.

# Answer
> 1 votes
I just used Texture Packer to do just as you ask:

```
for file in *.pvr.ccz; do
  /Applications/TexturePacker.app/Contents/MacOS/TexturePacker $file --sheet ${file%.pvr.ccz}.png --texture-format png --data ${file%.pvr.ccz}.plist
done

```

It gives you a PNG and a plist of the sprite data.

It also runs on most platforms, so even if you're not on a mac something similar should still work.

# Answer
> 0 votes
"Image Converter Plus" can convert PVR to JPG and PNG images. You can select and convert multiple images at same time.

---
Tags: textures
---


title: HUD Text not displaying/drawing

text:
# Question
Title: HUD Text not displaying/drawing
I am trying to use blueprints to display my character's speed using a HUD, but for some reason the text is not displaying. What am I doing wrong? I am using the First Person template.

# Answer
There are some mistakes in your try. The white lines are the execution path, the steps are executed in the order they are linked with the execution pins. In your picture you can see that the first "Cast To FirstPersonCharacter" has no execution pins connected. So this is never executed. And you use the output of this node as input for another cast node this value is null because the first cast has no input. Then you read the display name but not the velocity of the character. And again you did not connect the execution pins of the node where you try to set the string. So this step is skipped. In the end there is no value (null) that could be printed by the Draw Text node.

But now the solution:

You chose the HUD to show the text which is ok. Natively the hud draws the crosshair, which you can leave untouched. Simply put the part to draw the speed afterwards. Connect the execution output pin from the Draw Texture Node with your new nodes.
> 1 votes

---
Tags: unreal-4, unreal, first-person-shooter, blueprints
---


# Question
Title: How can I enable/disable a script that is attached to a character, only once?
With only once, I mean once false and once true. The reason I want to enable and disable the script is that I don't want to disable the player controller and then after some point re-enable that controller again.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float speed;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;
            var firstpc = fpc.GetComponent<FirstPersonController>();

            if (fpc.transform.rotation != Quaternion.Euler(0, 0, 0))
            {
                firstpc.enabled = false;
                fpc.transform.rotation = Quaternion.Slerp(fpc.transform.rotation, Quaternion.Euler(0, 0, 0), speed * Time.deltaTime);
            }
            if (fpc.transform.rotation == Quaternion.Euler(0,0,0))
            {
                firstpc.enabled = true;
            }
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

```

This script is not attached to the `FirstPersonController`. That is why I added the global variable fpc.

I'm getting the script that is already attached to the fpc. I called it firstpc and the script name is: `FirstPersonController`

`FirstPersonController` gives the player a control over the fpc with the mouse camera. I want to disable the script until `fpc.transform.rotation == Quaternion.Euler(0,0,0)` and then enabled the script again to use.

The problem is that it's all the time getting over and over again to the line:

```
firstpc.enabled = false;

```

Then it's getting also to the line:

```
firstpc.enabled = true;

```

But since it's getting to the false all the time it's stuck between both states.

The script here in my question is attached to the Plane in the hierarchy. And the script I want to enable/disable is attached to the `FPSController`.

In my script that is attached to the Plane, `fpc` is the `FPSController` and `firstpc` is the script `FirstPersonController` that attached to the `fpc`.

# Answer
> 0 votes
Solved it using a bool helper: rotated

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float speed;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;
    private bool rotated = false;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;

            if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                fpc.transform.localRotation = Quaternion.Slerp(fpc.transform.rotation, Quaternion.Euler(0, 0, 0), speed * Time.deltaTime);
            }

            if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))
            {
                fpc.GetComponent<FirstPersonController>().enabled = true;
                rotated = true;
            }
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

```

# Answer
> 1 votes
If the engine uses global variables, start the script off with a conditional statement that checks for whether the statement that uses Boolean is true. If so, then use :

```
If (Bool1 == true) {
(have statements to be executed here.)
}

```

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


# Question
Title: Building an Octree for terrain generation
I've previously implemented marching cubes/tetrahedra to render an IsoSurface. It worked (YouTube), but the performance was dire as I never got around to implementing variable Level of Detail based on view distance (or even removing old, distant chunks).

I decided to have another go and do it properly this time. I've started by creating an OctreeNode that works as follows when `Build()` is called.

* If the chunk is too small to build, return immediately.
* Work out if the surface passes through this chunk's volume.
* If so, then decide if we want to raise the LOD (because the camera is close)
* If so, then spawn 8 children and call the same process on them
* If not, build the mesh using the current node's dimensions

Some PseudoCode:

```
OctNode Build() {
    if(this.ChunkSize < minChunkSize) {
        return null;
    }
    densityRange = densitySource¹.GetDensityRange(this.bounds);
    if(densityRange.min < surface < densityRange.max) {
        if(loDProvider.DesiredLod(bounds)² > currentLoD) {
            for(i 1 to 8) {
                if(children[i] == null) {
                    children[i] = new OctNode(...)
                }
                children[i] = children[i].Build();
            }
        } else {
            BuildMesh();
        }
        return this;
    }
}

```

¹ As well as returning density at a point, the density source can determine the possible density range for a given volume.

² The LoD provider takes a bounding box and returns the max desired LoD based on camera position/frustum, user settings, etc...

So... This all works fairly well. Using a simple sphere as the Density source, and showing all nodes:

And just the leaves:

However, there are a couple of issues:

* I have to define the initial bounding volume (and the larger it is, the more processing I need to do)
* At the root of the tree, I have no idea how deep the leaves will be, so my LoD numbering starts at lowest quality (root) and increases as chunks get smaller. Because LoD is now relative to initial volume, it's not much use when I want to do things at specific sizes / qualities.

I've thought of a couple of options but both seem flawed:

* Maintain a collection of Octrees and add/remove depending on distance. Can't see how I'd mesh across nicely¹, plus I'd need a list of known-empty nodes, especially if I want arbitrary 3D surfaces (to avoid re-calculating empty volumes repeatedly)
* Add a parent Node to the current root, then add seven siblings for the original node. This would work and be on-demand but it seems complex to shrink back down sensibly as the player moves through the landscape. It would also make LoD numbers even less meaningful.

¹ \[In clarification to Q below\] At present, if 2 physically adjacent nodes in the tree are at different LODs, I have some code to coerce the verts such that there's no seam when the meshes are generated. I'm able to do this by knowing the the density for multiple of surrounding nodes. In a scenario where I have 2 independent octrees side-by-side, I'd have no easy way to retrieve this information, resulting in seams.

What's an optimal way to approach this?

# Answer
> 1 votes
I'm not sure I'm answering the exact question, so I'm going answer in segments, and feel free to reply in comments if there's a misunderstanding about the particulars of a specific question.

> I have to define the initial bounding volume (and the larger it is, the more processing I need to do)

This doesn't seem like it should be the case. Since the octree increases in granularity exponentially, adding a few levels at the top should be a very small net increase in performance hit.

> At the root of the tree, I have no idea how deep the leaves will be, so my LoD numbering starts at lowest quality (root) and increases as chunks get smaller. Because LoD is now relative to initial volume, it's not much use when I want to do things at specific sizes / qualities.

If you fix your root octree to some "large enough value" then "LoD relative to initial volume" shouldn't be an issue. And as mentioned above, I don't think having extra level at the top will impact overall performance.

> Maintain a collection of Octrees and add/remove depending on distance. Can't see how I'd mesh across nicely, plus I'd need a list of known-empty nodes, especially if I want arbitrary 3D surfaces (to avoid re-calculating empty volumes repeatedly)

As I understand it, this proposed solution is about lowering LoD when moving away from a previously detailed area. I figure it should look very similar to the "increasing LoD" code path:

```
if (loDProvider.DesiredLod(bounds) <(is a lot less than)< currentLoD) {
    for(i = 1 to 8) {
        children[i].Destroy();
    }
    BuildMesh();
}

```

Then, you're not spending *too* much time checking distant nodes because you can rely on the fact that while far away, there aren't too many "active" nodes, since all the higher-resolution nodes will have been removed.

---

> Assuming small nodes are rock-scale, that would mean potentially dozens if not hundreds of levels as I travel across a continent

I think the logarithmic scale of the octree makes it still feasible. If your top level is 1,000,0000,000 m wide (this would be 25 times wider than the real Earth, and with 625x the surface area) and your lowest level bits are 10cm across, that's 32 levels in the octree, which is *probably* manageable enough. If you wanted a planet 100 times wider than the Earth (and with 10000 times more surface area), that's only an additional 3-4 levels in your octree. At this point it would take a player hundreds of years to walk across the the world, and if you use naive floating point math the world will be accumulating precision errors.

> Maintain a collection of Octrees and add/remove depending on distance. Can't see how I'd mesh across nicely¹, plus I'd need a list of known-empty nodes, especially if I want arbitrary 3D surfaces (to avoid re-calculating empty volumes repeatedly)

Isn't this fundamentally equivalent to having the billion-km-wide octree but keeping a list of pointers to every, say, 1km block? Then "meshing across" would simply be relying on the 2km-size nodes. Keeping a local reference to each mid-level "large block" also keeps you from having to iterate through the top-level nodes, if you're worried about the "possibly dozens of additional octree levels"

---
Tags: unity, c#, voxels, octree
---


title: How to loop through colors?

text:
# Question
Title: How to loop through colors?
I want to loop between two color in unity

```
public float speed = 1.0f;
public Color startColor;
public Color endColor;
public bool repeatable = false;
float startTime;

// Use this for initialization
void Start()
{
    startTime = Time.time;
}

// Update is called once per frame
void Update()
{
    if (!repeatable)
    {
        float t = (Time.time - startTime) * speed;
        GetComponent<Light>().color = Color.Lerp(startColor, endColor, t);
    }
    else
    {
        float t = (Mathf.Sin(Time.time - startTime) * speed);
        GetComponent<Light>().color = Color.Lerp(startColor, endColor, t);
    }
}

```

# Answer
> 3 votes
Use Mathf.PingPong to lerp between your colors

```
private float duration = 5 ;
private Light lightComponent ;

private void Awake()
{
    lightComponent = GetComponent<Light>();
}

void Update()
{
    float t1 = Mathf.PingPong(Time.time - startTime, 1) / duration;
    float t2 = (Mathf.Cos( ( (Time.time - startTime) + duration ) * Mathf.PI / duration ) + 1 ) * 0.5f

    // Use t2 instead of t1 if you want smoother interpolation
    lightComponent.color = Color.Lerp(startColor, endColor, t1);
}

```

Desmos plot showing t2

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


title: How do you update time based resources?

text:
# Question
Title: How do you update time based resources?
im currently writing a simple server for a mobile/web game. In short, players have a number of buildings that will produce several items every x minutes. What i though as a solution its creating a column named "nextProduction" and start a cronjob that will give the items and update that column, then renew the cronjob for the next iteration.

Now i have doubt about it, maybe this solution will be too resource intensive as the number of players increase? Thanks beforehand

# Answer
## TL;DR

I suggest you use **lazy evaluation**. Skip to 3) to learn more.

## 1) Don't optimize too early

First we need to define what you mean by "resource intensive". Which resource? CPU? Disk space? I/O? What's the bottleneck?

The usual approach is to build something first, profile it or stress test it until it begins to fail, and then look at which resources got maxed out. If your program reaches 100% CPU usage before it reaches 100% memory usage, then the CPU is the *bottleneck* \- in other words, you are CPU-constrained.

Now, for the game you're describing, I assume the current number of resources for each player will be stored in a database. If so, then database I/O will most likely be your bottleneck, because each run of the updating a row on a database is *relatively* expensive compared to, say, updating a value in memory.

Updating those cronjobs might also be expensive depending on where they are stored. Crontabs are usually stored on the disk (and disk I/O is expensive) but sometimes they are stored in memory instead. It depends on whether you want persistence.

That being said, "expensive" is relative. Modern servers are fast. Your approach might scale better than you think. If you need to scale it even further, it might be cheaper to pay for extra hardware than to invest the man-hours to optimize it.

## 2) Suggested improvements

Updating a cronjob and the database on each run is unnecessarily complex. For starters, let's try updating only one thing at a time. Here's your database schema:

```
resourceAmount INT | productionCooldown INT | lastResourceDrop DATETIME

```
* Run a cronjob every **second** (or every 500 milliseconds... set this to whatever you want).
* On every run, the job should check every row in the resources table. For every resource:
* 1. determine how much time has passed since the last update (`elapsedTime = currentTime - lastResourceDrop`)
* 2. determine how many resources the player got during that time: `resourcesToAdd = floor(productionCooldown / elapsedTime)`
* 3. add the amount of time it took for them to get those resources: `lastResourceDrop = lastResourceDrop + productionCooldown * resourcesToAdd`

This is less complex, and therefore easier to troubleshoot, compared to the approach with multiple cronjobs. However, now we're iterating over every row of the database every single second, which is suboptimal. Here's how we can improve this further:

## 3) Lazy evaluation

Create a `getPlayerResource` method or API and use it whenever *anything* in your game wants to know the **current** amount of resources a player has. This method should:

* Update the player's resources by following the steps above.
* Return the player's current resource amount.

**Pros:**

* No cronjobs
* It only updates resources for **active** players. Inactive players won't slow down your algorithm.
* Thread safe. If you perform all the database operations as a transaction, you won't run into corner cases where you update a player's resources twice in a row.

**Cons:**

* Slightly slower than just reading a player's current resources without performing any checks or updates.
> 1 votes

---
Tags: architecture, server
---


# Question
Title: How can i get component script from FirstPersonCharacter?
In the Hierarchy i have a FPSController and as child of it FirstPersonCharacter. I can get script that attached to the FPSController but not from the FirstPersonCharacter.

What i want to get is the Blur script from the FirstPersonCharacter.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public CharacterController firstPersonCharacter;
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float speed;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;
    private bool rotated = false;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;

            if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                fpc.transform.localRotation = Quaternion.Slerp(fpc.transform.rotation, Quaternion.Euler(0, 0, 0), speed * Time.deltaTime);
            }

            if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))
            {
                fpc.GetComponent<FirstPersonController>().enabled = true;
                firstPersonCharacter.GetComponent<Blur>
                rotated = true;
            }
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

```

I can get scripts from the FPSController like this:

```
fpc.GetComponent<FirstPersonController>().enabled = true;

```

But i can't get the Blur script from the firstPersonCharacter. I tried before instead:

```
public CharacterController firstPersonCharacter;

```

With GameObject:

```
public GameObject firstPersonCharacter;

```

But Blur is not exist. When i make GetComponent The Blur is not exist.

# Answer
FirstPersonCharacter itself does not have Blur component, but the GameObject that has it attached does:

```
[SerializeField] FirstPersonController FPC; /// <summary>Your First Person Controller.</summary>
/// Option 1.
private Blur blur; /// <summary>Blur's Script.</summary>
/// Option 2.
[Serializefield] GameObject objWithPFCAndBlur; /// <summary>So you could get both components from this GameObject.</summary>

void Awake()
{
    blur = FPC.gameObject.GetComponent<Blur>();
    if(blur == null)
    { /// As a good practice, you should do null checkings, on cases like this.
         Debug.LogError("There was no Blur attached to GameObject");
    }
    else /// Continue...
}

```

Maybe you had problems because Components (such as Rigidbodys, MonoBehaviours, Colliders, etc) can have Components attached (so you can use GetComponent() method), but what usually you do on inspector is attaching Components to a GameObject, which was the case, FPC does not have a Blur attached, as you can see on your GameObject's inspector.

Hope that solves your issue.
> 1 votes

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


# Question
Title: How to make a 2D semicircle sprite in Unity?
I followed this answer: https://answers.unity.com/questions/1008644/semi-circle-2d-collider.html and was able to create a semicircle collider:

But is there any way I can just crop the circle sprite to make it a semicircle?

I tried looking for other documentation, but couldn't find any..

# Answer
Mmmmm, maybe you could just crop the sprite on an image editor and then import it to unity. Seems like the most reasonable way to do it.

Or maybe you could generate on unity half the sprite with something like this:

```
    /// <summary>Converts Sprite to Texture2D.</summary>
    /// <param name="_sprite">Sprite to copy pixels from.</param>
    /// <returns>Texture2D with Sprite's pixels.</returns>
    public static Texture2D ToTexture(Sprite _sprite)
    {
        Texture2D newTexture = new Texture2D((int)_sprite.rect.width, (int)(_sprite.rect.height / 2));

        Color[] pixels = _sprite.texture.GetPixels
        (
            (int)_sprite.textureRect.x,
            (int)_sprite.textureRect.y,
            (int)_sprite.textureRect.width,
            (int)(_sprite.textureRect.height / 2) /// Here you crop the sprite on half
        );

        newTexture.SetPixels(pixels);
        newTexture.Apply();
        return newTexture;
    }

```

But that's something you should do once, since it is expensive, and this is applied to a Texture2D, and not a sprite.
> 1 votes

---
Tags: unity, sprites
---


# Question
Title: MCS character mouth open - is this mo cap animation problem?
I have MCS Female Character where I can assigned Mocap to my character. I have downloaded mixamo animation and assigned this to the character but the problem is, the character mouth remains open. I am not 3d artist or animation guy, so here are my question.

1. How can I solve mouth open problem in unity?
2. What is the reason that mouth is open? Either mocap data has open the mouth or what else problem?

# Answer
1. Go To **M3D character manager** component in your character
2. Go to **Advanced**
3. Check (True) **Force Jaw Shut**

Thanks to MCS team for answer
> 1 votes

---
Tags: unity, c#, animation, character, motion-capture
---


title: Python/Kivy game for steam

text:
# Question
Title: Python/Kivy game for steam
I'm developing a game in Python with Kivy as the gui. I've heard a few programs mentioned that compile python files to .exe's. However, I cant seem to find any that mention compiling .py and .kv files.

I wish to eventually publish my game to Steam Direct but i would like to know if my current approach to coding the game will hinder me doing so.

My actual question is, is there a way to compile a Python game with Kivy to an .exe file?

# Answer
> 3 votes
In the end, i found the answer hidden within their docs https://kivy.org/docs/guide/packaging-windows.html

You then need to set `console=True` to `console=False` within the .spec file to disable the console from being shown. Once you create the .spec file, you will see which line it is

---
Tags: python, steam
---


# Question
Title: How to handle a large number of pickups in a MMO game
How do games like Minecraft, or really any MMO game that has pickups, handle them?

Say terrain spawns 3 pickup drops of "dirt" everytime you dig said terrain. Say every item has a rotation animation computed every frame. If the number of pickups in the world goes very high, that would be a useless massive overhead in the frame computation for a client in a given server, as it's likely that a lot of those pickups items are light years away from you.

So what I thought is that you have to "do stuff" only with the pickups close to the local player, but still this would imply that every frame I have to check if any other pickup item is close enough that it has to start animating.

My actual question is: how have other MMOs solved this issue?

# Answer
By simply only loading those parts of the world into memory which are close to the player. Anything else is suspended to hard drive. When there is a tiny object laying around two kilometers away, then the player can not see it and can not interact with it. So there is no reason to update it or send it to the GPU for rendering. The smaller the object and its interaction range, the lower the range around the player where you need to load it.

Regarding finding out what's close to the player: That mostly boils down to storing the world in a datastructure optimized for spatial lookup. Good candidates for those are spatial hashing and multi-dimensional trees.
> 49 votes

# Answer
You have two very different things to manage:

1. The server **must** manage the entire world, in an authorative manner. For that, communication with N clients (where N is "massive") is necessary.
2. The client *could*, in principle, know about the entire world, but it *needs not*. For the client, it is sufficient to know about what's nearby the player. Assuming for example a rather coarse grid-like partitioning, it would need to know only the player's cell and the 26 cells around the player (or 8 cells in case you have a 2D grid). A somewhat finer grid is better, but you get the idea.

Now, *a lot* of pickups, what is "a lot"? You dig maybe 5 things per second, that's maybe two dozen numbers that need to be updated on the server, and the server *may* have to transmit those to some other player whose area of interest overlaps your cell. For a computer, this is quite ridiculous amount of data, and a neglegible amount of computation. It may become a challenge when there's hundreds/thousand of players in the same cell (then your paritioning is too coarse).

The server does not need to know, nor care about the rotation of the pickups or such details. Why would it?

The client actually doesn't care either, since this is just eye candy that the client can make up on the fly.

What's necessary from the server's point of view is knowing that you were digging at (30, 40, 50) in the node you're in, and it decides that this spawns e.g. three objects of type 5, or one object of type 7 with a count of 3. That's all it cares about, and it's all it tells you. It will also include that information in the data sent to someone moving his area of interest over the grid cell later (assuming it's still there by then).

The client gets told three objects spawned there, blah blah. Now, whether the client displays an ASCII-art map where there's now a 'D' or whether it shows a rotating pile of dirt, it's all the same. Whether the piles have different rotations or whether only the ones close to your player rotate is all the same, too. It's just stuff that is displayed on your monitor, it doesn't affect anyone else.

So, in the concrete case that you want to rotate only nearby piles of dirt, you can just do a range check on all the objects you know about. Since the data set isn't large, even brute force on *everything* will work.

You can (and should) depending on your partitioning size, trivially prune away grid cells that are too far away.

You can, of course, furher sub-partition your cell and use something super smart. Use a kd-Tree if you will, but do not expect huge gains. You can prune stuff away with Manhattan distace, or your can sort your stuff in a small grid of your own... but why?

A distance check (really squared distance, but it's the same to you) is a mere two multiplications and an addition (optimized to MUL, MADD, so really just two operations), followed by a branch or conditional move. That's pretty much as fast as any other operation which doesn't prune entire grid cells at a time. In fact, this is something that you *could* even do on the GPU...

Seeing how you will have a few hundred, or at most a few thousand distance checks against the same position (squared distance works fine), you really don't have much trouble just doing that calculation, even more so as it's a rather cache-friendly iteration over contiguous memory, and with conditional moves, it's dirt cheap. Something like (pseudocode) `rot = r[i] + 1; r[i] = ((dx*dx+dy*dy) < DIST_SQ) ? rot : r[i];`. That's one iteration over an array of a few hundred values per frame. The computer couldn't care less about doing that, it's contiguous loads and stores, simple ALU, no branches, and only a few thousand iterations.

This (many-to-one) is not the same class of problem (many-to-many) as on the server. Really, the client isn't the problem.
> 22 votes

# Answer
@T.Sar writes in a comment that you should look into Minecrafts "loaded chunk" concept for more information. If you do, be aware that this is rather complicated in Minecraft due to people building machines in the game.

A very simplified version follows:

The world is divided into square regions(chunks). In Minecraft there is also a height division but most mmos don't need that.

The game client only cares about the regions close to the player. This is much simpler than drawing a circle around the player, but perfectly good enough.

In Minecraft, the regions are 16x16 blocks, and the client knows about 9x9 regions, 4 regions out in each direction. (4 regions east + region player is in + 4 regions west = 9 regions total. Same north/south)

There is nothing magical about these numbers, use whatever makes sense in your game.

The client only animates things inside this area. The server only calculates things like wandering monsters in regions that is close to *some* player.

When a player walk around inside a region, nothing special happens, when they cross a region border the "edge of animation" is pushed one region over. The client then needs to ask the server about the regions it now sees.

There is nothing wrong with having several nested animation limits. E.g. animate item drops in a 3x3 area, wandering monsters in a 5x5 area and just show the landscape in a 9x9 area.

The server keeps a "frozen version" of regions which no player sees. If this takes a lot of memory, you may want to unload these after a time. When a player next arrives, the region is reloaded without the item drops. You need to be faster next time, Player 1.
> 2 votes

---
Tags: architecture, networking, performance, mmo
---


# Question
Title: Unity3d - Cannot implicitly convert type `UnityEngine.Ray' to `Ray'
I downloaded the free standard assets from the assets store, now I get alot of errors in my console. e.g.

```
Assets/SampleScenes/Scripts/PlaceTargetWithMouse.cs(19,35): error CS0029: Cannot implicitly convert type `UnityEngine.Ray' to `Ray'

```

This is the according script and I am not able to figure out why this happens, everything looks fine for me:

```
using System;
using UnityEngine;

namespace UnityStandardAssets.SceneUtils
{
    public class PlaceTargetWithMouse : MonoBehaviour
    {
        public float surfaceOffset = 1.5f;
        public GameObject setTargetOn;

        // Update is called once per frame
        private void Update()
        {
            if (!Input.GetMouseButtonDown(0))
            {
                return;
            }
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);    //<--- Error
            RaycastHit hit;
            if (!Physics.Raycast(ray, out hit))
            {
                return;
            }
            transform.position = hit.point + hit.normal*surfaceOffset;
            if (setTargetOn != null)
            {
                setTargetOn.SendMessage("SetTarget", transform);
            }
        }
    }
}

```

# Answer
Ok I was able to solve it, I renamed `Ray` to `UnityEngine.Ray`.

```
UnityEngine.Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

```
> 0 votes

---
Tags: unity
---


# Question
Title: How can i start rotating object slowly smooth and then stop the rotation also slowly smooth?
In the top of the script:

```
public FirstPersonController fpc;
public float speed;

```

In the Update

```
void Update()
{
  fpc.transform.localRotation = Quaternion.Slerp(fpc.transform.rotation,
  Quaternion.Euler(0, 0, 0), speed * Time.deltaTime);
}

```

The problem is that the rotation start immediately. And i want it to start slowly smooth then it will get some speed and then near the end to slowly smooth again until stop.

Update:

This is the complete script for now:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public UnityStandardAssets.ImageEffects.Blur blur;
    public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized;
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float startAcceleration = 0.6f;
    public float endAcceleration = 0.6f;
    public float maxSpeed = 1.0f;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;
    private bool rotated = false;
    private float rotationSpeed;
    private Quaternion clampedTargetRotation;
    private bool start;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;

            if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                rotationSpeed = Mathf.Clamp(rotationSpeed + startAcceleration * Time.deltaTime, 0, maxSpeed);
                rotationSpeed = Mathf.Clamp(rotationSpeed - endAcceleration * Time.deltaTime, 0, maxSpeed);
                clampedTargetRotation = Quaternion.RotateTowards(fpc.transform.localRotation, whateverRotationTokeepGoing, rotationSpeed * Time.deltaTime);
                fpc.transform.localRotation = clampedTargetRotation;
            }

            if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))
            {
                fpc.GetComponent<FirstPersonController>().enabled = true;

                blur.enabled = false;
                blurOptimized.enabled = false;

                rotated = true;
            }
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

```

My problem is in the rotation part:

```
if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                rotationSpeed = Mathf.Clamp(rotationSpeed + startAcceleration * Time.deltaTime, 0, maxSpeed);
                rotationSpeed = Mathf.Clamp(rotationSpeed - endAcceleration * Time.deltaTime, 0, maxSpeed);
                clampedTargetRotation = Quaternion.RotateTowards(fpc.transform.localRotation, whateverRotationTokeepGoing, rotationSpeed * Time.deltaTime);
                fpc.transform.localRotation = clampedTargetRotation;
            }

```

The rotation should start from the current fpc rotation state and end at 0,0,0 This is where the rotation should be end when fpc is 0,0,0

```
if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))

```

If fpc rotation is at 0,0,0 then stop. Between the start and stop make the whole rotation operation.

# Answer
Just add an angular acceleration to your angular speed, the starting acceleration and the ending acceleration can be different:

```
void Update()
{
    float speed;
    Quaternion clampedTargetRotation;

    if(start)
    {
       speed = Mathf.Clamp(speed + startAcceleration * Time.deltaTime, 0, maxSpeed);
    }
    else
    {
       speed = Mathf.Clamp(speed - endAcceleration* Time.deltaTime, 0, maxSpeed);

    }

       clampedTargetRotation = Quaternion.RotateTowards(fpc.transform.localRotation, whateverRotationTokeepGoing, speed * Time.deltaTime);
       fpc.transform.localRotation = clampedTargetRotation;
}

```

N.B. this is just a "sketch" of solution
> 1 votes

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


title: how do i make AI enemy in unity 2D?

text:
# Question
Title: how do i make AI enemy in unity 2D?
How do i make a AI enemy that go to player and if enemy arrives at collision (ex. stone collider) rotating to path , (unity 2D top view)?

(Enemy has a face sprite and animator component) In this pic , I want to do :ai enemy following player but when arrives to wall so it's face changes the path and following again . 2- if enemy 1 arrives to enemy2 so enemy face change the path for follow player

# Answer
> 0 votes
You have multiple challenges baked into one here:

1. Get an enemy to chase the player
2. Get an enemy to respect the other objects in your scene
3. Have the enemy find a valid path around the object

The first two are quite simple to get working, the third requires a more complex solution, either using ray-casting for very simple scenarios, or actual path-finding such as A\* maps or similar. In this latter case, implementing it is quire a lot more tricky.

Either way, I would recommend you do some more searching on the first two, there are plenty of solutions to this problem already. I did a quick search and found these:

chase player: https://answers.unity.com/questions/274809/how-to-make-enemy-chase-player-basic-ai.html

for changing direction: https://answers.unity.com/questions/284206/change-direction-on-collision-problem-1.html

There are also a lot of basic tutorials on these on youtube. Either way, you can't simply copy paste a solution, as you will need to understand what is unique to your game world.

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


# Question
Title: Attach component of other Object to a variable within Unity Inspector
This question might sound a bit stupid and I'm sure there is a simple solution for this .. I'm just not finding it:

Actually all I want to do is attach the `MeshRenderer` Component of this Object

to a variable of a script on another Object like

**Problem: As soon as you click on the `Capsule` Object ofcourse the Inspector changes to this Object and I cannot drag in a component to the previous selected Object anymore.**

I know there are a lot alternatives like linkin only the GameObject e.g. as `MeshObject` and later in code refer to `MeshObject.GetComponent<MeshRenderer>` but I wondered if this can be done directly, too.

# Answer
I'm glad you solved your problem!

Two other solutions you can use:

1. If the component you want to assign is the only one of its type on its GameObject:

* Select the object with your recipient script (`Custom Network Transform` in this case)
    * In the hierarchy view, click and drag the GameObject with the component you want to assign, dropping it on the recipient field.
    * Unity will automatically select the first Component on the dragged object that matches the type of the field.
2. If there are multiple components of the same type on the source object, and you want to select a specific one:

* Right click on the tab at the top of the inspector and choose Add Tab -\> Inspector
    * Now you have two inspector tabs! Drag one out / dock it elsewhere so you can see both inspectors at once.
    * Select your source object, and both inspectors will show you its components
    * At the top-right of the inspector, you'll see a little lock icon. Click this on one of the inspectors to change it to its locked state.
    * Now select your recipient object. The unlocked inspector will update to show its components, while the locked inspector keeps showing the source object's components.
    * Now you can drag components / references between the two objects.
> 2 votes

# Answer
Ok never mind just found it.

Click on the little circle next to the variable - it allows you to browse through all type-matching elements that exist in your scene/assets.

On this way I also learned that it makes sence to give also MeshObjects reasonable names ;)
> 1 votes

---
Tags: unity
---