# Question
Title: convert view space normal to world normal
Im writing a shader that uses Unity's \_CameraDepthNormalsTexture to get both the view normal and depth values. I return a color from my fragment shader equal to the normal values sampled.

I am having problems converting the view normal into a world normal so that when my camera tilts around, the fragment colors shouldnt change.

How can turn my view normal-\> world normal in my fragment shader? Relevant code is marked with TODO below:

```
Shader "Custom/DepthNormal"{
    Properties {
       _MainTex ("", 2D) = "white" {}
       _HighlightDirection ("Highlight Direction", Vector) = (1, 0,0)
    }

    SubShader {
        Tags { "RenderType"="Opaque" }
        Pass{
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D _CameraDepthNormalsTexture;
            sampler2D _CameraDepthTexture;

            struct vertexOutput {
                float4 position_in_clip_space : SV_POSITION;
                float2 depth : TEXCOORD0;
                float4 scrPos : TEXCOORD1;
                float4 position_in_world_space : TEXCOORD2;
            };

            vertexOutput vert(appdata_full v){
                vertexOutput output;
                output.position_in_clip_space = UnityObjectToClipPos(v.vertex);
                //use the helper function instead of MATRIX_MVP as per documentation
                //mul(UNITY_MATRIX_MVP,float4(v.vertex,1.0));

                output.position_in_world_space = mul(unity_ObjectToWorld,v.vertex);
                //recall computeScreenPos does not divide by w, but because this is not an image effect,
                //diving by w here will WARP things unless we are completely parallel to viewing camera

                output.scrPos = ComputeScreenPos(output.position_in_clip_space);

                return output;
            }

            float4 frag(vertexOutput input) : COLOR
            {
                float3 normalValues;
                float depthValue;
                //extract depth value and normal values

                //recall computeScreenPos does not divide by w, so if you want proper screenUV for use in tex2D divide
                //xy by w
                //https://forum.unity3d.com/threads/what-does-the-function-computescreenpos-in-unitycg-cginc-do.294470/

                float2 screenUV = input.scrPos.xy / input.scrPos.w;
                //DecodeDepthNormal(tex2Dproj(_CameraDepthNormalsTexture, input.scrPos), depthValue, normalValues);
                //Alternatively:
                    DecodeDepthNormal(tex2D(_CameraDepthNormalsTexture,screenUV), depthValue, normalValues);

                 //TODO: CONVERT TO WORLD NORMAL?
                 float4 worldNormalValues  = mul(unity_ObjectToWorld,mul(UNITY_MATRIX_IT_MV, float4(normalValues,1.))); //THIS ISNT RIGHT :(

                float d = pow(depthValue,2);
                return float4(normalValues.x,normalValues.y,normalValues.z,d);
            }

         ENDCG
        }

    }
fallback "Diffuse"
}

```

# Answer
If all we're transforming is normals (directions, not positions), then we can take a little shortcut:

```
float4x4 viewTranspose = transpose(UNITY_MATRIX_V);
float3 worldNormal = mul(viewTranspose, float4(viewNormal.xyz, 0)).xyz;

```

In this case we're only using the upper-left 3x3 block of the view matrix, which should generally be a pure rotation matrix. A nice property of rotation matrices is that transposing them produces their inverse cheaply. This undoes the camera's orientation, rotating the normal back into worldspace.

It does not correctly invert the translation component, but since we're zeroing-out and discarding the w, this won't impact the normal directions.

---

If you need to do this for points with translation, then we'll need a proper inverse which is not as convenient to compute in the shader. The simplest thing is to capture the matrix we want on the C# side and upload it as a uniform that all shaders can reference, similar to the built-in matrices Unity offers.

We can attach a script like this to the camera to do that work automatically, just before the camera renders the scene:

```
[RequireComponent(typeof(Camera))]
public class ViewMatrixInverter {

    int variableID;

    void Start() {
        variableID = Shader.PropertyToID("UNITY_MATRIX_IV");
    }

    void OnPreRender() {
        Shader.SetGlobalMatrix(variableID, transform.localToWorldMatrix);
    }
}

```

Then in the shader we can read this matrix by declaring a uniform:

```
float4x4 UNITY_MATRIX_IV;

```

And inside the fragment program we can use this matrix to transform viewspace normals OR points:

```
float3 worldNormal = mul(UNITY_MATRIX_IV, float4(viewNormal.xyz, 0)).xyz;

float3 worldPoint = mul(UNITY_MATRIX_IV, float3(viewPoint.xyz, 1)).xyz;

```
> 1 votes

---
Tags: unity, shaders, normals
---


title: Why my stencil mask doesn't work?

text:
# Question
Title: Why my stencil mask doesn't work?
I've a very sipmle Unity scene.

It has two objects in it, which is Sprites, and they both use sipmle black boxes as a textures.

Here's two shaders, one should act as a mask, and second as a object, that should be rendered only in pixels, specified by that mask.

Mask shader:

```
Shader "Unlit/StencilUnlitShader"
{
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
    Tags { "RenderType"="Opaque"
    "Queue" = "Geometry" }

    Pass
    {
        //AlphaTest Greater 0.5 //Only render pixels whose alpha is greater than AlphaValue.
        Stencil{
        Ref 2
        Comp Never//Never - never pass the stencil test, Always - always pass the stencil test
        Pass Replace //write Ref value into the stencil buufer
        }

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float2 uv : TEXCOORD0;
            float4 vertex : SV_POSITION;
        };

        sampler2D _MainTex;
        float4 _MainTex_ST;

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.uv = TRANSFORM_TEX(v.uv, _MainTex);
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            // sample the texture
            fixed4 col = tex2D(_MainTex, i.uv);
            //if (col.a < 0.9) discard; //discard a pixel if it's transparent and don't draw it into a buffer
            return col;
        }
        ENDCG
    }
}
}

```

Object shader:

```
Shader "Unlit/GreenUnlitShader"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
    }
        SubShader
    {
        Tags{ "RenderType" = "Opaque"
              "Queue" = "Geometry+5" //to draw after stencil object
    }

        Pass
        {
        //AlphaTest Less 0.5
        Stencil{
        Ref 1
        Comp Less //Always, Less - if ref value is greater then current value in the stencil buffer
        Pass Keep
        }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

    struct appdata
    {
        float4 vertex : POSITION;
        float2 uv : TEXCOORD0;
    };

    struct v2f
    {
        float2 uv : TEXCOORD0;
        float4 vertex : SV_POSITION;
    };

    sampler2D _MainTex;
    float4 _MainTex_ST;

    v2f vert(appdata v)
    {
        v2f o;
        o.vertex = UnityObjectToClipPos(v.vertex);
        o.uv = TRANSFORM_TEX(v.uv, _MainTex);
        return o;
    }

    fixed4 frag(v2f i) : SV_Target
    {
        fixed4 col = tex2D(_MainTex, i.uv);//fixed4(0,1,0.5,0.6);
        //if (col.a < 0.9) discard;
        return col;
    }
ENDCG
    }
    }
}

```

The problem is, this doesn't seem to work, and object doesn't seems to be rendered at all (why it should in the places where mask have it's pixels)

# Answer
> 2 votes
In your mask shader, change comp never to comp always.

You never write to the stencil because the comp fails.

---
Tags: unity, stencil, shaderlab
---


# Question
Title: How do I customise automatically-generated script?
When you create a script via the Unity editor, it generates a script with some pre-formatted code.

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

public class GenericClass : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
}

```

When I create a script, I am generally guaranteed to use additional code, such as a namespace or a custom editor. Furthermore, I almost *always* delete content from the automatically-generated script. Is there a way to change the automatic code generated by Unity?

# Answer
In addition you can also

1. Add an editor script in Assets/Editor folder that subscribes to `OnWillCreateAsset` where you can parse the output and modify it. For example script that would automatically insert namespace could look like following:

```
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

using UnityEditor;

public class InsertNS : UnityEditor.AssetModificationProcessor
{
    public static void OnWillCreateAsset(string path)
    {
        string assetPath = Regex.Replace(path, @".meta$", string.Empty);
        if (!assetPath.EndsWith(".cs")) return;

        var code = File.ReadAllLines(assetPath).ToList();
        if (code.Any(line => line.Contains("namespace"))) return;//already added by IDE

        //insert namespace
        int idx = code.FindIndex(line => line
            .Contains("class " + Path.GetFileNameWithoutExtension(assetPath)));
        code.Insert(idx, Regex.Replace(
        assetPath.Replace('/','.'), @"^([\w+.]+)\.\w+\.cs$", "namespace $1 {\n"));
        code.Add("}");

        //correct indentation
        for (int i = idx + 1; i < code.Count - 1; i++) code[i] = '\t' + code[i];

        var finalCode = string.Join("\n", code.ToArray());
        File.WriteAllText(assetPath, finalCode);
        AssetDatabase.Refresh();
    }
}

```
2. Insert own control sequences into templates for easy replacing in `OnWillCreateAsset`, e.g.

```
finalCode = finalCode.Replace(@"#date#", DateTime.Now);

```
3. Add more templates to the template folder, for example one for Singleton pattern - Unity is not limited to single script template.
4. The visual studio code snippets are way to customizing creating new scripts (...and even further - new script parts). For example, a code snippet for private `SerializeField` might come in handy. After importing `privateField.snippet`:

```
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>
        Serialized private field
      </Title>
      <Author>Myself</Author>
      <Description>Adds private serializable field visible to Unity editor</Description>
      <Shortcut>pf</Shortcut>
    </Header>
    <Snippet>
      <Imports>
        <Import>
          <Namespace>UnityEngine</Namespace>
        </Import>
      </Imports>
      <Declarations>
        <Literal>
          <ID>FieldName</ID>
          <ToolTip>Replace with field name.</ToolTip>
          <Default>myField</Default>
        </Literal>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[[SerializeField] float _$FieldName$;]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

```

to *Tools/Code Snippet Manager/My Code Snippets* you can just type "pf" double tab and type the field's name. E.g.:

```
//"pf" tab tab "speed" produces
[SerializeField] float _speed;

```

Even more convenient would be snippets for often repeated longer sequences, e.g. readonly property backed by `SerializeField` field.
5. Visual studio also offer very powerful code generation tool, the T4 Text Templates(EF is using T4), though I personally find the practical use for Unity projects doubtful - they are overkill, quite complicated and the compilation of project would likely become dependent on Visual Studio.
> 4 votes

# Answer
You can find the script templates for automatically generating code in your Unity installation folder. I find the templates under *"Unity/Editor/Data/Resources/ScriptTemplates"*, while other sources have found it under *"Unity/Editor/Data/Resources"*.

The generic UnityScript and C# templates are identified as the files *"82-Javascript-NewBehaviourScript.js.txt"* and *"81-C# Script-NewBehaviourScript.cs.txt"*, respectively. You can directly edit these files to change the way in which Unity auto generates script.

You can also include additional templates, which will appear when you select *"Create"* from the *"Project"* window. Templates do not *appear* to require unique numbering, and use the initial string to determine the menu hierarchy, where "\__" denotes a submenu. For example, having a file named *"81-C# Script\__Editor Script-NewBehaviourScript.cs.txt"* will give you an additional "*C# Script"* menu, with the sub option to create an *"Editor Script"* using this template.

Do ***not*** rename the original templates; these are used more directly, by the engine. For example, renaming *"81-C# Script-NewBehaviourScript.cs.txt"* will prevent you from adding new C# scripts as components, directly through the inspector.

---

Below is my own example, though it demonstrates particular practices that I am most custom to. For example, I prefer to have my custom editor script in the same file as the target class, so I encapsulate it in `#if UNITY_EDITOR .. #endif`, instead of placing it in a generic "do not compile in build" editor folder.

I am not sure if it is even possible to provide the context of a custom namespace; I simply use "NAMESPACE", as this allows me to provide the correct namespace post-creation, using the commonly-inbuilt "find..replace all" function.

---

### The Template:

```
/* Created by Gnemlock */

using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace NAMESPACE
{
    public class #SCRIPTNAME# : MonoBehaviour
    {
        /// <summary>This method will be called at the start of each frame where this
        /// instance of <see cref="NAMESPACE.#SCRIPTNAME#"/> is enabled.</summary>
        void Update ()
        {
            #NOTRIM#
        }
    }
}

namespace NAMESPACE.UTILITY
{
    #if UNITY_EDITOR
    [CustomEditor(typeof(#SCRIPTNAME#))] public class #SCRIPTNAME#Editor : Editor
    {
        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            #SCRIPTNAME# s#SCRIPTNAME# = target as #SCRIPTNAME#;
        }
    }
    #endif
}

```

### The Output:

```
/* Created by Gnemlock */

using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace MyNamespace
{

    public class UpdatedClass : MonoBehaviour
    {
        /// <summary>This method will be called at the start of each frame where this
        /// instance of <see cref="MyNamespace.UpdatedClass"/> is enabled.</summary>
        void Update ()
        {

        }
    }
}

namespace MyNamespace.UTILITY
{
    #if UNITY_EDITOR
    [CustomEditor(typeof(UpdatedClass))] public class UpdatedClassEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            UpdatedClass sUpdatedClass = target as UpdatedClass;
        }
    }
    #endif
}

```
> 14 votes

---
Tags: unity
---


# Question
Title: Numerical differentiation to calculate size of circular buffer
I'm using Allegro 5 to create a software-generated "motion blur" effect for my 2D sprites. I basically just have a boost::circular\_buffer of some length which holds "snapshots" of the sprite going back in time. Each render cycle a new "snapshot" of the main sprite is pushed onto the front of the buffer, and the last is popped off the back. The "snapshots" are then rendered with alpha values scaled by how old/far back in the buffer they are.

To save on CPU power I'd like to have the circular buffer dynamically resized so that the length of the trail is proportional to the object's velocity, i.e. don't store and push back lots of snapshots for trail sprites that won't be needed anyway because the object is moving too slowly.

The inputs I have to the data structure that holds the main sprite and its associated effect buffer are just the dx and dy values of how much its position vector changed since the last update cycle of the game logic. So I'm looking for a suggestion for an algorithm that can use that to increment/decrement some kind of unsigned counter that can be used to resize the buffer proportional to velocity.

# Answer
> 1 votes
If the velocity can change over time, I would start with either a moving average (i.e. the average over the last N number of frames) or a moving max (i.e. the max value seen over the last N frames) & here's why:

Let's say your object starts out fast & then slows down. Initially, you'd have a large buffer & then switch to a smaller one. If you suddenly down size your buffer by an appreciable amount, the result will be visibly noticeable - probably jarringly so. Suddenly up sizing your buffer is also a bit problematic - what do you fill the extra slots with? You could space out your existing data & fill in the holes with replicated frames, but that may defeat the original goal of reducing the processing.

A somewhat related idea is to not use a moving target for the buffer size, but to use a dynamic correction. By that I mean, say your buffer is currently size N & your current measure of displacement gives you a target of size M. Then on every frame thereafter, increase or decrease the buffer by some small delta until the buffer size hits your target. Ideally, your delta will be big enough that it doesn't take too long to hit your target, but small enough to not create artifacts. You'll need to experiment a bit to find a balance. You could also use a proportional delta so that large changes will be accommodated more quickly than small ones.

In either case, the idea is to not change your buffer size too quickly.

All that being, I'm not sure the premise of saving CPU power is sound. If a lot of dynamic resizing is needed, the allocation / deallocation churn may be counter productive. On the other hand, if you don't need a lot of resizing, then why bother?

Also, I wouldn't put the sprite image data (i.e. he pixels themselves) into the buffer. Instead, I would buffer the indices of the desired sprite (i.e. a reference to look up the pixels). Moving the image data to the buffer & then to the screen has more overhead than moving the index into the buffer & then using the buffer to look up the desired image data & moving that to the screen.

---
Tags: physics, algorithm, allegro
---


# Question
Title: How do I reverse "Cartesian->Isometric" function?
I'm working on an isometric tile rendering engine and I need to reverse a function I used to translate the Cartesian coordinates into isometric coordinates. I've already written a function for this, but I've been getting a strange logical error and I think it must be somewhere in my code for translating from isometric coordinates back into Cartesian. Anyways, here's the code for translating Cartesian-\>Isometric

```
    private Vector2 cartToIso(Vector2 init){
        Vector2 iso = new Vector2();
        iso.x = (((init.x - init.y) * TILE_WIDTH_HALF))+X_OFFSET;
        iso.y = MAP_HEIGHT-TILE_HEIGHT-((init.x + init.y) * TILE_HEIGHT_HALF);
        return iso;
    }

```

Any suggestions would be appreciated. Also if anyone was wondering, what I'm trying to do right now is create an algorithm for tile picking in my engine. The API(LibGDX) is a little strange in the sense that it uses a bottom-up Y coordinate system but with any of the input(ie, clicks) it uses a top-down Y coordinate system. I can post the code I have for tile picking later if anyone thinks they can help me more, but I'll save it for now since it's pretty long.

Edit: This is the method I use to reverse it, and it seems to be giving me the incorrect results. Does this look correct?

```
    private Vector2 isoToCart(int x, int y){
        Vector2 cart = new Vector2();
        x = x-X_OFFSET;
        y = y-MAP_HEIGHT;
        cart.x = (x / TILE_WIDTH_HALF + (y / TILE_HEIGHT_HALF)) /2;
        cart.y = (y / TILE_HEIGHT_HALF -(x / TILE_WIDTH_HALF)) /2;
        return cart;
    }

```

# Answer
> 3 votes
If you ignore the constants you have in your calculations (such as tile width, for example) the calculations for isometric to cartesian and back are usually;

```
float isometricX = cartesianX - cartesianY;
float isometricY = (cartesianX + cartesianY) * 0.5f;

```

And the reverse is

```
float cartesianX = (2.0f * isometricY + isometricX) * 0.5f;
float cartesianY = (2.0f * isometricY - isometricX) * 0.5f;

```

That's assuming square tiles of unit length.

I'm not sure how your `MAP_HEIGHT` plays into this, but you should be able to scale that by your tile size to get the values need for your game.

Edit; To use this to pick a tile the following method could be used (note that here `tileSize` is the height of the tile, so in your case 32px);

```
private Vector2 screenToMap(float screenX, float screenY) {
    float mapx = (screenX / tileSize + screenY / (tileSize * 0.5f)) * 0.5f;
    float mapy = (screenY / (tileSize * 0.5f) - (screenX / tileSize)) * 0.5f;
    return new Vector2(mapx - 0.5f, mapy + 0.5f); // -.5/+.5 because the drawing isn't aligned to the tile, it's aligned to the image
}

private Vector2 cartesianToIsometric(float cartesianX, float cartesianY)  {
    float isometricX = (cartesianX - cartesianY);
    float isometricY = (cartesianX + cartesianY) * 0.5f;
    return new Vector2(isometricX, isometricY);
}

```

The above doesn't take a viewport into account, so you'll have to do panning and zooming yourself, or you could rely on libGDX's viewport.

I knocked up a pure java example of this where I draw the map, get the map coordinate of the mouse and pick tiles; Isometric sandbox

(again, this isn't actually isometric but I think it's what you are looking for).

**Edit:** When doing this in a libGDX application, under a `OrthographicCamera`, you need to unproject screen coordinates to camera space, then call my `screenToMap` function as that works on unprojected coordinates.

So at the beginning of the map's render you need to do something like this;

```
public Vector2 unproject(OrthographicCamera camera, Vector2 position) {
  Vector3 unprojected = camera.unproject(new Vector3(position.x, position.y, 0));
  return new Vector2(unprojected.x, unprojected.y);
}

private Vector2 screenToMap(Vector2 screen) {
  float mapx = (screen.x / tileSize + screen.y / (tileSize * 0.5f)) * 0.5f;
  float mapy = (screen.y / (tileSize * 0.5f) - (screen.x / tileSize)) * 0.5f;
  return new Vector2(mapx - 0.5f, mapy + 0.5f); // -.5/+.5 because the drawing isn't aligned to the tile, it's aligned to the image
}

public void render(OrthographicCamera camera, Vector2 mousePosition) {
  Vector2 mp = screenToMap(unproject(camera, mousePosition));
  spriteBatch.setProjectionMatrix(camera.combined);

```

Fact that libGDX has a y-axis that increases as you go up on the screen doesn't matter, the unproject will fix that for you as you'll also render in the different direction.

For sake of completion, here's a link to a libGDX application of what I am explaining here: libGDX source. It will render a map and highlight the cell you're over with the mouse.

I assume you're doing this because you want to learn, because if you just want a isometric map in your game, libGDX comes with Tmx-classes that can load and render a isometric map created in for example Tiled.

# Answer
> 0 votes
```
function isoToCart (isoX, isoY, isoZ = 0) {
    const x = (isoY - isoX) / 2;
    const y = (isoY + isoX) / 2 - isoZ;
    return { x, y };
}

function cartToIso (cartX, cartY) {
    const x = cartY - cartX;
    const y = cartY + cartX;
    return { x, y };
}

```

above are reversible no need to thank me by +1

sorry for javascript but you get the math

---
Tags: java, libgdx, mathematics, tilemap, isometric
---


# Question
Title: Unity3D to Android: CommandInvokationFailure: Unable to convert classes into dex formatc
I could not get past the error below. I already tried finding duplicated plugins but there are none and I am still getting errors when building in Unity3d to an Android.

Plugins Used:

* FacebookSDK
* UTNotifications

Unity Log Error:

```
CommandInvokationFailure: Unable to convert classes into dex format.
/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java -Xmx2048M -Dcom.android.sdkmanager.toolsdir="/Volumes/projects_main/Android/SDK/tools" -Dfile.encoding=UTF8 -jar "/Applications/Unity/PlaybackEngines/AndroidPlayer/Tools/sdktools.jar" -

stderr[
warning: Ignoring InnerClasses attribute for an anonymous inner class
(com.jcraft.jsch.Channel$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(com.jcraft.jsch.ChannelSftp$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(com.jcraft.jsch.ChannelSftp$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(com.jcraft.jsch.JSch$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(com.jcraft.jsch.Util$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.LogFactory$3) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.LogFactory$4) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.LogFactory$5) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.LogFactory$6) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.LogFactory$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.LogFactory$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.impl.LogFactoryImpl$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.impl.LogFactoryImpl$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.impl.LogFactoryImpl$3) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.impl.SimpleLog$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(org.apache.commons.logging.impl.WeakHashtable$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(com.vladium.util.exception.ExceptionCommon$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.

trouble processing "javax/xml/XMLConstants.class":

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.

Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/vladium/app/IAppVersion;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/vladium/emma/AppLoggers;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/vladium/emma/Command;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/vladium/emma/EMMAException;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/vladium/emma/EMMAProperties;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/vladium/emma/EMMARuntimeException;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/vladium/emma/IAppConstants;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/vladium/emma/IAppErrorCodes;

UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.RuntimeException: Translation has been interrupted
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:613)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:311)
    at com.android.dx.command.dexer.Main.run(Main.java:277)
    at com.android.dx.command.dexer.Main.main(Main.java:245)
    at com.android.dx.command.Main.main(Main.java:106)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at SDKMain.main(SDKMain.java:129)
Caused by: java.lang.InterruptedException: Too many errors
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:605)
    ... 9 more
]
stdout[
processing archive /Volumes/projects_main/Bitbucket/MyWishingWell/Temp/StagingArea/android-libraries/animated-vector-drawable-23.4.0/libs/./classes.jar...
processing android/support/graphics/drawable/AnimatedVectorDrawableCompat.class...
processing android/support/graphics/drawable/AnimatedVectorDrawableCompat$1.class...
processing android/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState.class...
processing android/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableDelegateState.class...
processing android/support/graphics/drawable/animated/BuildConfig.class...
processing archive /Volumes/projects_main/Bitbucket/MyWishingWell/Temp/StagingArea/android-libraries/appcompat-v7-23.4.0/libs/./classes.jar...
ignored resource .readme
processing android/support/v7/app/ActionBar.class...
processing android/support/v7/app/ActionBar$DisplayOptions.class...
processing android/support/v7/app/ActionBar$LayoutParams.class...
processing android/support/v7/app/ActionBar$NavigationMode.class...
processing android/support/v7/app/ActionBar$OnMenuVisibilityListener.class...
processing android/support/v7/app/ActionBar$OnNavigationListener.class...
processing android/support/v7/app/ActionBar$Tab.class...
processing android/support/v7/app/ActionBar$TabListener.class...
processing android/support/v7/app/ActionBarActivity.class...
processing android/support/v7/app/ActionBarDrawerToggle.class...
processing android/support/v7/app/ActionBarDrawerToggle$1.class...
processing android/support/v7/app/ActionBarDrawerToggle$Delegate.class...
processing android/support/v7/app/ActionBarDrawerToggle$DelegateProvider.class...
processing android/support/v7/app/ActionBarDrawerToggle$DrawerArrowDrawableToggle.class...
processing android/support/v7/app/ActionBarDrawerToggle$DrawerToggle.class...
processing android/support/v7/app/ActionBarDrawerToggle$DummyDelegate.class...
processing android/support/v7/app/ActionBarDrawerToggle$HoneycombDelegate.class...
processing android/support/v7/app/ActionBarDrawerToggle$JellybeanMr2Delegate.class...
processing android/support/v7/app/ActionBarDrawerToggle$ToolbarCompatDelegate.class...
processing android/support/v7/app/ActionBarDrawerToggleHoneycomb.class...
processing android/support/v7/app/ActionBarDrawerToggleHoneycomb$SetIndicatorInfo.class...
processing android/support/v7/app/AlertController.class...
processing android/support/v7/app/AlertController$1.class...
processing android/support/v7/app/AlertController$2.class...
processing android/support/v7/app/AlertController$3.class...
processing android/support/v7/app/AlertController$4.class...
processing android/support/v7/app/AlertController$5.class...
processing android/support/v7/app/AlertController$AlertParams.class...
processing android/suppor<message truncated>

```

# Answer
> 1 votes
Dex format errors happen when their are multiple files that are the same. Deleting files that are the same will probably resolve the problem.

# Answer
> 1 votes
Maybe those two plugins are some same android .jar, and thus importing them created a duplicate in your Plugins/Android folder.

Check if you have two android-support jars in that folder and delete one.

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


# Question
Title: Should I create a Lua wrapper classes for my C++ classes, or should I bind them directly?
I have a fairly standard architecture like this:

`GameObjects` have `Transform`, and can have `Renderer`, `Rigidbody`, `Camera`, `LightSource`, etc, and all of these classes have their corresponding methods.

* `GameObject` has `GetName`, `SetName`, etc. and its own `Transform`.
* `Transform` has `GetPosition`, `SetPosition`, etc.
* `Renderer` has `SetTexture`, `SetMaterial`, etc. and references a `Transform`/`GameObject`.

If I want to implement Lua scripting using LuaBridge, and I would like to achieve an **API** similar to this...

```
function update()
    local gameObject = this()
    local renderer = gameObject:GetRenderer()
    renderer:SetTexture("Brick")
    local rigidbody = gameObject:GetRigidbody()
    rigidbody:SetMass(10)
    local transform = gameObject:GetTransform()
    transform:SetPosition(1, 10, -5)
end

```

...then which of these should I choose?

**Solution A:**

* I bind every C++ class directly to Lua classes.

+ In this way I have to implement some extra scripting quality-of-life methods for the classes, so no big deal.
    + But it's not so easy to see whether a method is callable in Lua script, or is only available in native code. (for example I need to name method `XYZ` as `LuaXYZ`)
    + Methods which are only created so that scripting is made easier, are mixed with core functionality.

**Solution B:**

* I create a wrapper class for every required class, like: `Renderer->RendererHandler`, `Transform->Transform Handler`, `GameObject->GameObjectHandler`, etc.

+ Lua and core functionality is separated, much easier to see what is the scripting API and what is not.
    + For every class I have to create another similar class which got a lot of methods, which are just calling the calling the same method in the wrapped class. Like `GameObjectHandler->GetName()` just calls `GameObject->GetName()`

Thanks in advance.

**Summary:**

* In my opinion, Solution B is the best. That is the easiest to handle, the most transparent, and the most separated.
* But I got lots of new classes and new dependencies, which messes up my clean architecture. Solution A makes expanding functionality much easier to handle (I dont have to create a lua interface class for new components).
* But error handling is worse, because I don't have to care about if a scripter uses a `NULL` pointer (like a non existent component)
* But if that happens due to my engine implementation I'll have to handle it seriously. (And how can I signal whether a `NULL` pointer in a method is "don't care type" or "serious problem" type?)
* **So currently I think that the best solution is this:**

```
class GameObject {
   ...

   GetName()
   SetName()

   Lua_getName()
   Lua_setName()

   ...

```
* I don't have to create "Lua interface" classes, and handle that mess that comes with it.
* I directly bind the Lua functions to the classes, but I create new methods in that class for scripting purposes.
* For example I implement `GetName()` for "InEngine" functionality, and a `Lua_getName()` which is bound to Lua functions and used only in scripts.
* The problem here is that, yeah you can't call InEngine methods from Lua because it's not bound. **But what about calling `Lua_getName()` instead of `GetName()`?**

+ There is no compile check for that, and if the developer is tired and makes this mistake, it will be hell to debug that.

# Answer
> 2 votes
C++ aliases seem to provide a solution to your problem.

**Solution A**

The main benefit here is low maintenance. The other is you can avoid method call indirection overheads by avoiding wrappers (I imagine that will have multi-`JMP` overheads, FWIW).

Problem 1 remains knowing what constitutes your Lua interface and what is internal, without having to wrap method calls. To get around that, I would suggest that you name the *actual* methods with the `Lua-` prefix, while giving these methods aliases that lack said prefix. Now your existing internal code can continue to use the old names, but you can see at a glance in your class which methods are Lua-accessible. Extra QoL methods sit neatly alongside these, with same `Lua-` prefix.

Problem 2 is nested method calls which should ideally be avoided, and while it is conceivable that your compiler of choice optimises these out, I wouldn't rely on it (especially optimising across distinct classes as in your Solution B). Fortunately aliases, as a compile-time mechanism, solve this problem.

I recommend this solution based on its simplicity.

**Solution B**

Provided the above doesn't work out for whatever reason, this is desirable as you suggest, in terms of maintaining a clean separation of interfaces (engine internals vs. scripting).

What you **don't** want is the hassle of maintaining this new layer. Frankly, you should not have to, for it ought to be easy enough to automate generation of that layer when changes occur. You'd need to integrate this with your build process, however - which is more work.

Philipp rightly suggests somehow annotating those methods which you wish some wrapper generator (SWIG) to process. Try putting some unmistakable string inside one-line comments preceding each such function, search for that string, and have the wrapper generator operate on that. I can't be more specific than this, as it is going to hinge on what generator you end up using and what its capabilities are in terms of reading annotations - e.g. SWIG, some other third party's, or your own home-brewed.

You might write your own text parser to run over source code and identify such methods, then pass names of those methods into your generator to generate necessary interfaces. Devil is in the details.

If your compiler does not optimise out the indirection of method calls through your wrapper class, you're going to end up with marginally worse performance, although negligible in 98% of cases.

**Conclusion**

While you are actively developing infrastructure, *do not* tie yourself into solutions that are going to increase the cost of change unless you have an exceedingly good reason to do so. You need to be able to remain agile through much of your production, even if codebase organisation is not ideal. In this case that means avoiding Solution B - even if you get it working nicely, at the very least you'll frequently have to run your interface generator. Provided that doesn't add much time to each build, or it's very infrequent, it may be okay for you... the problem there is, you have to implement it before you'll know. Catch-22 situation. My gut feel is increased complexity is best avoided at this (early?) stage. I also think the entire point of something like LuaBridge, which you are using, is to maintain agility.

---
Tags: c++, architecture, lua
---


# Question
Title: Switch axes and handedness of a quaternion?
I have a quaternion, coming from a system with the following:(intertial sensor)

```
Right handed.
Forward direction: Y axis
Right direction: X axis
Up direction: Z axis

```

I need to convert this into a coordinate system that is: (Unreal engine)

```
left-handed.
Forward direction: X axis
Right direction: Y axis
Up direction: Z axis

```

I have tried negating the axis, and angle, I have tried switching values, i cannot get this to work. All help greatly appreciated! I am working in C#, with `Microsoft.Xna.Quaternion.`

# Answer
> 7 votes
To convert the Quaternion, we need to convert the imaginary part (xyz) which represents the axis of rotation into the destination coordinate system. In this case, that means exchanging x & y while leaving z unchanged.

Then, because we've changed the handedness of our coordinate system, our angle takes the opposite sign (a +ve rotation in a right-handed coordinate system is a -ve rotation about the corresponding axis in a left-handed coordinate system). This leaves the real part (w) unchanged, since cos(theta) = cos(-theta), and negates the imaginary part, since sin(theta) = -sin(-theta)

Combining these two effects, we get the following:

```
Quaternion ConvertSensorToUnreal(float x, float y, float z, float w) {

    Quaternion output;
    output.x = -y;
    output.y = -x;
    output.z = -z;
    output.w = w;

    return output;
}

```

# Answer
> 1 votes
Rotation - counter clockwise is +ve and clockwise is -ve

Rx(90)\*Rz(-90)\*Ry(90) will switch in the way you wanted. Either you perform these rotation using quaternions or convert them into DCM (Direction Cosine Matrix) and then perform the rotation and convert back to quaternions.

I hope this will solve your issue.

---
Tags: xna, quaternion
---


# Question
Title: Keeping balance between widely different character classes
So I've been theory-crafting an idea for a game I think would be interesting, but I'm trying to work out the kinks in my idea. Here's my dilemma:

Let's say a player can choose between two classes, being a foot soldier or piloting a large vehicle like a tank. To keep gameplay diverse, there needs to be some players as foot soldiers and some as tanks. In games such as BF4, the individual soldier has so many anti-vehicle weapons that vehicles are actually somewhat weak. Is there a good way to balance classes such that an endgame infantry unit is equal(not inferior or superior) to a vehicle such as a tank or ship?

I was also thinking of an AI squad mechanic, where the player can command a small number of AI foot soldiers, so this might be worked into the balancing. I'm just trying to think of a way to have all classes be appealing to the player.

# Answer
In UT2004 Onslaught mode, vehicles spawned infrequently. Players in their own skins can respawn instantly but can't constantly be in heavy vehicles as the average respawn time for vehicles in that game is about 2 minutes. So basically when you climb into a vehicle you "are" that vehicle, but you are limited as to the amount of vehicle-piloting you can do. While the vehicles are spawning, the foot soldiers have to keep doing the work of trying to win the battle. Have the spawn time depend on the strength of the vehicle. Motorbikes might only take a minute to respawn, while tanks and gunships might take 5 minutes. This reflects construction and/or shipping times for large, complex vehicles.

Other than that, foot soldiers have sabotaged tanks in a variety of ways during the World Wars, and still do to this day with various weaponry. Tanks have always been, by nature, low in agility and in their ability to detect infantry before they can become a threat. The same was true of the tanks of yore: Knights. It's the nature of armour. While I'm sure modern tanks have all kinds of sensors to detect incoming infantry, the trouble is still dealing with infantry effectively once they arrive. Drones are a modern possibility for anti-infantry purposes; see C&C Generals. Mixing unit types is, in most games, the most effective deterrent to this paper/scissors/stone effect of one unit being weak against another.

As for squads, UT2004 shows how on average 3 skilled footsoldiers have a good chance at taking out a Goliath tank. Usually one or two of them will be killed beforehand, but that's the tradeoff for being able to destroy one of the game's more powerful weapons platforms. So I think you're on the right track.
> 3 votes

---
Tags: game-design, balance
---


title: PyGame for Python 3.5

text:
# Question
Title: PyGame for Python 3.5
I am running Python 3.5 and I want to install PyGame, the website only supports up to version 3.2. I have tried a few forums on this and other websites but they are all for Python 3.4. Does anyone know were I can find the install file for Python 3.5 and how to install it?

# Answer
You didn't specify which OS you are using, but I just successfully installed PyGame directly from Mercurial on OS X for Python 3.5.1 (via Homebrew, `brew install python3`) with the following command:

```
pip3 install --user hg+http://bitbucket.org/pygame/pygame

```

This should work on Linux as well.

```
% python3.5
Python 3.5.1 (default, Feb 16 2016, 16:10:36)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
>>> pygame
<module 'pygame' from '/Users/thp/Library/Python/3.5/lib/python/site-packages/pygame/__init__.py'>

```

I haven't tried on Windows, but this blog post has some suggestions on how to make compiling Python C extensions on Windows work, for different Python versions -- apparently you just need to install Visual Studio 2015 Community Edition.
> 1 votes

# Answer
If you are on Windows and you have installed Python via Anaconda (which I recommend) you can simply open Anaconda prompt and simply type `pip install pygame` and you 'll get the latest version.
> 1 votes

---
Tags: python, pygame
---


# Question
Title: Cocos2d-x setContentSize, setScale give poor graphic quality
I want to create sprite with size is relative to the screen size. I.e: Sprite size is equal to screen width * 0.2.

I use `setContentSize` and `setScale` but it gives ugly and poor graphic quality. I've read about multiple resolution supports, but it doesn't work on this case because i need sprite size adapt to the any screen size.

Testing on iPhone 7, i scale an image from 512x512 to 64x64.

This is error of cocos2d-x or anyway to archive it?

# Answer
On the iphone7 the width is 1334 pixels. If you go \*.2 thats 20 percent of the screen = 266.8.

My suggestion: Start at the highest resolution you want your final game to support (1k, 2k?). Create the proper biggest size image you need for your top resolution and logical smaller versions for inbetween resolutions to support. Understand how appdelegate.cpp implements sizes. Load the sprite at the proper size. If there's an in game reason you want to scale your image down in engine then make sure you're generating mipmaps.

setContentSize doesn't do what you're trying to do, it affects the sprites texture rect. Use setScale by itself.
> 0 votes

---
Tags: graphics, sprites, cocos2d-x, scale
---


# Question
Title: How to know if an actor is touched in libgdx?
I am using "Gdx.input.isTouched()" in the render method of my Screen method, to know where is touched, but when the touch is dragged in the screen, it also activates the events i want only when an actor is touched.

Is there any listener to know when an Actor is touched, but the event is not the dragged one, im doing it with sprites.

# Answer
There's a `TouchUp` and `TouchDown` method if I'm not mistaken. You need to keep track of state.

I handle this in my projects by creating a custom `MyAwesomeSprite` class; on `TouchDown`, I just set `_isTouched=true`, and on `TouchUp`, I set `_isTouched = false`. This allows me to detect dragging (touch-down triggered when `_isTouched` is already true), so I can easily distinguish between these two cases.
> 1 votes

# Answer
Add a Listener to the actor like so. Note you need an InputMultiplexer so your Stage and Screen can both handle touches. Add the Stage first so it gets clicks first, then in the Listener call event.handle() and return true otherwise the touch will bubble through and be picked up by your Screen too.

```
actor.addListener(new ClickListener(){
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                doSomething(x,y,pointer);
                event.handle();//the Stage will stop trying to handle this event
                return true; //the inputmultiplexer will stop trying to handle this touch
            }
        });

```

Some actors will require

```
Actor.setTouchable(Touchable.enabled);

```
> 2 votes

---
Tags: android, sprites, libgdx, touch
---


# Question
Title: How to use HyperLink with Actor in Libgdx
I am making a quiz game using LibGDX. I want it to redirect to a website. I am using classes like Text and Label that extends Actor to write text using a bitmap Font. I have no idea on how to provide a link (like anchors in html) in a native app. However, I am not very good at Android but know java well. In android , I saw on stackexchange, we can do so using Intent or string.xml configuration.

Can anyone suggest me a way to do so using Actor in libGDX?

# Answer
```
        TextButton button = new TextButton("click me", skin);
        button.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                super.clicked(event, x, y);
                Gdx.net.openURI("https://www.example.com");
                event.handle();
            }
        });

```
> 2 votes

---
Tags: android, libgdx
---


# Question
Title: Cannot draw around the screen after zooming out with LibGDX projection coordinate
I've just started developing game in android using LibGDX. I've follow some samples and now my simple game can draw path when user move their finger around the screen.

now problems appear when i add another feature to allow user to **pinch zoom in and out**. after zooming OUT the orthographic camera user can still draw the path BUT the path can no longer follow user finger to the edge of the screen, the user can only draw the path around the center of the screen. looks like the coordinate projection after zoom out not changed and still limited to the projection before zoom out!

how can i make my game to keep drawing line around the entire screen even after the user have zooming out the camera?

here's my code:

*1.* in my `Screen` implemented class:

```
@Override
public void render(float arg0) {
    Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);

    renderer.render();
}

@Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        // TODO Auto-generated method stub
        isDrawing = true;

        Vector2 v = new Vector2(screenX, Gdx.graphics.getHeight()-screenY);

        //add new point for drawing path
        inputPoints.insert(v);

        return true;
    }

```

*2.* in my `Renderer` class:

```
cam = new OrthographicCamera();
    cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    this.cam.update();

public void setZoom(float zoom) {
     this.cam.zoom = zoom;
     this.cam.update();
 }

//the triangle strip renderer
    path = new PathClass();

public void render() {
    cam.update();
    batch.setProjectionMatrix(cam.combined);

    //generate the triangle strip from our path
    Array<Vector2> xox = screen.path();
    path.update(xox);

    //the vertex color for tinting, i.e. for opacity
    path.color = Color.WHITE;

    //render the triangles to the screen
    path.draw(cam);
}

```

*3.* on my `PathClass`:

```
public void draw(Camera cam) {
    if (tristrip.size<=0)
        return;

    gl20.begin(cam.combined, GL20.GL_TRIANGLE_STRIP);
    for (int i=0; i<tristrip.size; i++) {
        if (i==batchSize) {
            gl20.end();
            gl20.begin(cam.combined, GL20.GL_TRIANGLE_STRIP);
        }
        Vector2 point = tristrip.get(i);
        gl20.color(color.r, color.g, color.b, color.a);
        gl20.vertex(point.x, point.y, 0f);
    }
    gl20.end();
}

```

# Answer
> 0 votes
```
Vector3 v = new Vector3(screenX, Gdx.graphics.getHeight()-screenY, 0);

camera.unproject(v);//converts v to world coords

```

---
Tags: android, libgdx
---


title: Why is my transform stretching?

text:
# Question
Title: Why is my transform stretching?
I've read a lot about transformations: model to world space, world to camera space and projection transformationsl but when programming it, I can't get things right. I think I'm missing something, so here is my example code:

```
package com.test.rendering;

import...

public class Test extends ApplicationAdapter {
Texture texture;
Matrix4 projection;
Matrix4 transform;
SpriteBatch batch;
float angle = 0f;

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

    projection = new Matrix4();
    projection.setToProjection(
            -width / 2,
            width / 2,
            -height / 2,
            height / 2,
            1,
            100);

    batch = new SpriteBatch();
    batch.setTransformMatrix(transform);
    batch.setProjectionMatrix(projection);

    texture = new Texture("badlogic.jpg");
    Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}

@Override
public void render () {
    Gdx.gl.glClear(Gdx.gl.GL_COLOR_BUFFER_BIT);

    angle = (angle + 0.5f * Gdx.graphics.getDeltaTime()) % 360;

    transform = new Matrix4();
    //translate the world so we can see the texture at z = 0
    transform.translate(0.0f, 0.0f, -5.0f);
    transform.rotate(Vector3.X, angle);

    batch.setTransformMatrix(transform);

    batch.begin();
    batch.draw(texture, -texture.getWidth() / 2, -texture.getHeight() / 2);
    batch.end();
}

@Override
public void dispose () {
}
}

```

If you run this code you will see a very weird transformation: the texture starts rotating, but then stretches until some part of the screen, and then slowly disappears. I was expecting to see the texture just rotating around the x axi, with no stretching. Why is this happening? What is wrong with my code?

# Answer
Personally I always just use an OrthographicCamera like so:

```
    camera.setToOrtho(false, viewportWidth, viewportHeight);
    camera.position.set(x, y);
    camera.update();
    batch.setProjectionMatrix(camera.combined);

```

That's all you need for a spritebatch. Not sure why you're using Matrix4.setToProjection() that is for 3d, I think you might want to use MAtrix.setToOrtho2d(x, y, w, h); But I would recommend just using a camera.
> -2 votes

---
Tags: opengl, libgdx, graphics-programming
---


# Question
Title: An efficient way for generating smooth circle
I'm looking for creating smooth circle. OpenGL supports point, line, and triangle. To create other primitives like circle, we utilize the preceding shapes. In my case, I've utilized points as follows:

```
float radius(0.5f);
for ( float angle(0); angle < glm::radians(360.0f); angle += glm::radians(0.5f) ){
    Vertex vertices[] = { Vertex(glm::vec3( radius*cos(angle), radius*sin(angle), 0)) };
    meshes.push_back(   new Mesh(vertices, sizeof(vertices)/sizeof(vertices[0]), 'P')   );
}

```

In rendering loop,

```
while( Window.isOpen() ){
    Window.PollEvents();
    Window.clear();
    //================( Rendering )=========================
    Shader.Use();

    for ( int i(0); i < meshes.size(); ++i )
        meshes[i]->draw();

    //======================================================
    Window.SwapBuffers();
}

```

The result is

Now to create smooth circle, basically I just increase the number of points. I don't like this approach since I need to create a lot of points for single shape. **My question** is is there an alternative yet efficient approach for this issue?

# Answer
Here's one neat trick you can use to draw nice antialiased curves.

1. Take a mesh (eg. a quad, or to reduce unnecessary overdraw far from the line, you can use an annulus-shaped mesh that approximates the circle more closely.
2. Ensure the mesh's texture coordinates run from -1 at one edge of the circle to +1 at the other edge, to keep our math simple. Ensure there's a little more mesh past the -1...1 range so our circle doesn't run right into the hard polygon edge.
3. Use a fragment shader something a bit like this:

(I'm most familiar with HLSL syntax, so please let me know if I've made any errors translating this to GLSL)

```
// Compute this fragment's distance from the center of the circle in uv space.
float radius = length(textureCoordinate);

// Convert to a signed distance from the outline we want to draw.
// +ve: outside the disc, -ve: inside the disc.
float signedDistance = radius - 1.0f;

// Use screenspace derivatives to compute how quickly this value changes
// as we move one pixel left or right / up or down:
vec2 gradient = vec2(dFdx(signedDistance), dFdy(signedDistance));

// Compute (approximately) how far we are from the line in pixel coordinates.
float rangeFromLine = abs(signedDistance/length(gradient));

// Combine with our desired line thickness (in pixels) to get an opacity.
float lineWeight = clamp(THICKNESS - rangeFromLine, 0.0f, 1.0f);

return vec4(COLOR.rgb, lineWeight);

```

While just drawing a dense polygon with straight-line segments as suggested above by Theraot is likely to be more efficient, this shading technique is convenient because it automatically adapts to the scale of the circle / zoom of the camera to show a smooth curve, without needing to add more points as the camera gets closer. It also gives partial opacity along the edge of the line for a smooth antialiased look. It won't look good at extreme glancing angles though, since at the end of the day it's a flat sheet of geometry and has no thickness when viewed edge-on - you'd want to switch to a different shape if viewing the circle this way.
> 10 votes

# Answer
There's always the pure shader rendering thechnique if you really want to make it faster, but it only helps if you draw hundreds of circles, and they overlap.

Basically, you draw a rectangle that covers the whole screen, then you load each circle in the fragment shader including the radiuses. You look through each circle and see if the current fragment position is inside a circle with the formula

```
(x - centerX)^2 + (y - centerY)^2 < radius^2

```

(You should load in the squared radius to the fragment shader).

If it's inside the circle, check if the current circle is the closest one to the point, if it is, then fill fragment in with the circle's color.

I'm not saying you should use it, but if you need to draw lot of circles, it could help
> 4 votes

---
Tags: opengl, c++, shaders
---


# Question
Title: What's the difference between Camera::getPosition() and Camera::getPositionForViewUpdate()?
In Ogre3d, what's the difference between methods `Camera::getPosition()` and `Camera::getPositionForViewUpdate()`, official documentation doesn't says much:

```
/** Get the derived position of this frustum. */
const Vector3& getPositionForViewUpdate(void) const;

/** Retrieves the camera's position.*/
const Vector3& getPosition(void) const;

```

Thanks!

# Answer
> 0 votes
You probably don't want to call `getPositionForViewUpdate`, preferring instead `getPosition` or (as I'll explain below) `getRealPosition`.

---

`getPosition` returns the camera's `mPosition` member variable, while `getPositionForViewUpdate` returns the camera's `mRealPosition` member.

So what's the difference in these members?

An Ogre camera can optionally be attached to a scene node parent. When this is done, the camera's position (`mPosition`) is considered relative to the parent node. `mRealPosition` is always the world-space position of the camera.

When the camera is considered dirty and needs to be updated (for example, if it was moved between the current frame and the last), Ogre will check if the camera is parented to a node and if so compute the real position based on the local position relative to the parent. You can see this in the source code here:

```
// Ok, we're out of date with SceneNode we're attached to
mLastParentOrientation = mParentNode->_getDerivedOrientation();
mLastParentPosition = mParentNode->_getDerivedPosition();
mRealOrientation = mParentNode->convertLocalToWorldOrientation(mOrientation);
mRealPosition = mParentNode->convertLocalToWorldPosition(mPosition);
mRecalcView = true;
mRecalcWindow = true;

```

But if the camera's not attached to a parent, it simply does:

```
mRealOrientation = mOrientation;
mRealPosition = mPosition;

```

So in general, `getPosition` returns the camera's local position relative to its parent. If it has no parent, this will be the camera's position in world space. `getPositionForViewUpdate` will return the camera's position in world space regardless, *however*, it does not force an update of the camera because it is expected that `getPositionForViewUpdate` is only called during an update; it's an optimization.

In the general case if you want to get the camera's world position without having to think about whether or not the camera has a parent, call `getRealPosition`, which forces the update of `mRealPosition` if applicable before returning it.

---
Tags: camera, ogre, frustum
---


# Question
Title: Tree of objects in 2D space - children relative to parent
### Question

How do we track the position of child objects, relative to a parent?

---

### Context

I have a simple structure that keeps track of a point in space, along with zero or more children:

```
function Point(x, y){
  this.x = x;
  this.y = y;
  this.children = [];
}

```

Given the relationship:

```
const a = new Point(100, 100);
const b = new Point(10, 10);
a.children.push(b);

```

When these are rendered, I want point `b` to render at world location `[110, 110]`.

After moving `a` and only `a`:

```
a.x += 10;

```

Both points move and the distance between the two must remain the same.

After moving `b` and only `b`:

```
b.x += 10;

```

Only `b` moves and the distance between both points must now be different.

In other words, a child's `(x, y)` is the same as its offset from its parent.

# Answer
With transform hierarchies (trees), the normal method is to work your way up or down the tree, applying any transformations of the parent to the child, at each level, till you have processed everything. Given you aren't concerned with issues like rotation/orientation or scaling, i.e. you're purely interested in translation, it's very simple:

```
//...do your parent-child links and set up the offset (localPosition) for each node...

root.worldPosition = root.localPosition; //root has no parents so no nested translation
root.TransformChildren();

this.TransformChildren = function()
{
   for (var childKey in this.children)
   {
      var child = this.children[childKey];
      child.worldPosition = child.localPosition + child.parent.worldPosition;
      child.TransformChildren(); //child is the new parent
      //...its children can now add its position to their own to arrive at final value
   }
}

```

Notice that we use pre-order depth-first traversal to solve the problem. This is so that the parent positions have already been calculated for the children to use once we get down to the child level. You could use breadth-first search too, but DFS is just simpler in this instance.
> 2 votes

---
Tags: javascript, transformation, gameobject, objects, tree
---


# Question
Title: 2D Infinite scrolling terrain on two axes
There seems to be a lot of posts about endlessly scrolling backgrounds on one axis, but not much for a 2-axis solution. As Josh Petrie suggested, I'm posting my approach as an answer to see if anyone can improve on it.

**Game Requirements:**

I'm creating a 2D game for iOS using SpriteKit and Swift, but this paradigm could work for any touch-screen platform. The game involves a player sprite exploring an infinite field of outer space from a top-down 2D perspective. They drag their finger on the screen to move with scrolling behavior similar to panning a map in the Google Maps or Apple Maps apps.

The player should be able to scroll in any direction along the X and Y axes indefinitely. The texture of the 2D space terrain could be generated and drawn programmatically. Or it could take a limited number of textures made by an artist and recycle those images repeatedly to produce the endless terrain.

Planets and other objects will be added to the map, so there will have to be a way to add these into the terrain as well. Initially, these objects can appear at random, but with a frequency that feels natural (i.e. you can't have too many planets or too few). Later, the location of planets will need to be retained so the player can revisit them. So a mapping system will have to be implemented eventually, and that data stored in memory. For now, that is not necessary but a solution that future-proofs against that necessity is preferred.

# Answer
**My Infinite Terrain Approach:**

I have started with an approach that favors completing this task as soon as possible at the cost of performance optimization.

1. Create an invisible node with a physics body and add a gesture recognizer. When players swipe the screen, it moves the invisible node.
2. Make a textured sprite and add it as a child of the invisible node. The textured sprite is a one of several pre-made tiles that can be repeated to produce the endless terrain.
3. Start with one central tile, then write a `spawnTiles()` function that surrounds the first tile on all sides with new tiles. You can call this function for any new tile to surround that tile with more new tiles. But since this will cause tiles to overlap with other tiles, you need a way for the tiles to know if another tile already exists on all of its sides.
4. Add a small physics body that protrudes from each side of your tiles to act as a "sensor". When a sensor makes contact with another sensor, you know there is a another tile on that side. In the screenshot below, the green squares are sensors that lie on an open edge; the red squares are sensors that are contacting another sensor. (In production these sensors would be invisible).
5. Keep calling the `spawnTiles()` method until the screen is completely textured with a significant buffer beyond the frame of the screen. Now players can scroll the terrain and have the illusion that their player sprite is moving through space.
6. Continuously measure the distance from each tile to the center of the screen. When the edge of the terrain is too close to the center of the view, generate new tiles along the edges so the player never sees any holes in the terrain. If a tile gets too far from the view, destroy that tile to conserve memory.

**Analysis:**

This is my first SpriteKit game project and I am still getting familiar with the API and libraries. This approach seemed like the quickest way to the terrain working. I expected the iPhone 6 & 7 series (my target platforms) would be sufficient to absorb the extra overhead. However, this feels like a clunky and inelegant approach. It also appears to be rather processor-intensive.

When I ran the scene pictured above in the iPhone 7 simulator, the debugger showed that the CPU was holding at just under 100%. Granted, I'm currently using an arbitrary 1500 × 2668 texture for the tiles which is much larger that I would end up using once I move beyond prototyping.

Still, this approach uses a lot of physics bodies which seems unnecessary and I believe are rather expensive. The whole idea of creating additional objects to detect the tile edges also seems like a very kludgy way to do things. I feel like there must be a better way to handle this sort of two-axis scrolling.

In summation, here are what I see as the pros and cons of this approach.

**PROS**

* Super fast & easy to get the scrolling behavior working
* Easy to tweak the scrolling behavior by adjusting physics body properties

**CONS**

* Greater overhead due to extra physics bodies
* Every tile requires six additional node objects to act as sensors
* Dealing with the physics body interactions and juggling the sensor nodes creates additional complexity, potentially leading to technical headaches (as my Stack Overflow post illustrates)
> 1 votes

---
Tags: ios, procedural-generation, terrain, spritekit, scrolling
---


title: Driver AI in racing game

text:
# Question
Title: Driver AI in racing game
I'm curious how I could control cars in a racing game.

Should my AI agent control its car with commands like "throttle on 0.35, steereing wheel on 0.5 right, brake on 0.0"? Or should I rather pre-compute a curve the car sticks to, and visuals like front wheels turning are just to make everything looks consistent? Or is there any other way?

# Answer
> 17 votes
We can say that at some level the game is following a pre-computed path. Since the tracks of the racing game are (usually) a pre-computed path anyway.

Even if we are talking about generating the tracks by random, the game must have computed the current portion of the tracks for the moment where the car gets there.

*Well, that was easy. Anything else about it?*

Both, following a pre-computed path and controlling the car systematically have uses in the game industry. The answer is to use both, sort of.

First off, I want to mention that "computing a curve" can mean two things:

* Creating functions that will output the position on the curve, having as parameter how far on it you want to query.
* Creating a path, understood as list of points (or instructions and other control information) to follow.

The former can be useful for prediction or in some physic simulations. Yet, when we talk about controlling an object, the latter is the recommended approach.

*Note: For older games (1980's) the other cars where more like moving obstacles. They were there for you to avoid them and surpass them. We are not talking about those.*

---

* Following pre-computed a path: This is useful for cinematics or repeatable scenes. For example in GTA San Andreas the chase missions the chase target and all the cars follow a predefined path (this ensures that the chase target can avoid the traffic※). Yet, as soon as you perturb them they fall back to AI control, in this case the AI will have to path find to get to where it should be following its regular path.

※: In fact, it was prerecorded. Record and playback was one of the new features of the GTA SA game engine.
* Controlled by AI:

The AI at its simplest form is a state machine. It checks on what state it is and executes some action depending on that. I will be referring to these combinations of state and action as behaviors. The actions do not have to match the player's gamepad. Neither do the behaviors.

For a simple game, you probably only need two notable behaviors: 1) if it is on the tracks then follow the track avoiding other cars and any obstacles and 2) if it is not on the tracks, get back on the tracks.

At this stage, it is not far from following a path (the tracks). Yet, since the tracks are not really a line, we are not talking about following a path, but staying close to it (while avoiding other cars and any obstacles). Meaning that the AI has to solve “steering, braking and accelerating”.

For a modern game, the car will also be subject to physics simulation (to resolve collision and keep realism). Because of that, each iteration of the game loop the car will updated based on its speed and acceleration, and also “steering, braking and accelerating” (tweaks to speed) will be applied to follow the current behavior.

I also want to mention that modern games may have behaviors that are more complex, for example, the AI may choose to hit another car or to block their way. In fact, the AI may even choose which to apply based on some form of machine learning, but I digress.

Finally, consider that it may also be useful to have a simpler control for AI cars outside of player view. Either for performance or for Rubber Banding (which in this case keeps AI cars close to the player to keep the race interesting, it can be regarded as the AI cheating when you can't really leave behind any opponent).

---

About animation, it usually not a good idea to simulate physics for the wheels independently. If you do it, it would may add realism to the game, but will cost performance. Usually the game will animate the wheels based on the behavior instead of expressing the behavior in terms of movement of the wheels and simulating the consequences.

Of course, you may need to put additional consideration in whatever or not the wheels are in contect with the ground. And perhaps animating suspension.

# Answer
> 0 votes
I strongly recommend separating the car physics/state model from the car controller, and making the AI agent and the player controller be two kinds of interchangeable controller, with high level commands like the ones you suggested in your question.

This has a number of nice effects:

* You can implement and debug the physics/state model once for both player and AI
* Any new features of the physics/state model immediately apply to both the player and AI
* Player and AI cars behave consistently on the track, which increases perceived and actual fairness (if you want to handicap the racers, of course, you can do it by changing parameters on the cars)
* Various kinds of multiplayer support become much easier to develop.

This is a particular case of MVC separation, by the way.

---
Tags: game-design, ai
---


# Question
Title: Any way to visualize how will game objects look on different screens?
After completing my game and sending it to a bunch of friends with different devices, they complained about how some game buttons were too small. (I have developped a touchscreen game but after finishing and having issues with the touch detection I just decided I'd place buttons for controls on the screen. ) I obviously put all the button in a canvas, so it should normally scale with the screen and keep its anchor point, but the problem apparently is that it DID keep the anchor point, but it didn't scale, so even though the buttons looked pretty huge on my small sized game screen, and looked decent in an 480 x 800 emulator, it looked very mini sized in a 720x1280 phone. Any help on how I can make a button scale to the screen? Thanks!

# Answer
You can manually scale it by setting the size to be a percentage of the screen width/height. Make a variable(if you want) that is a value from 0.0 to 1.0 and multiply it by Screen.height(or .width). That is your new width/height. You should make the position relative also. Nevermind that part, you said the anchor works.
> 1 votes

# Answer
You can preview how your game looks with different sizes of screen and aspect ratios in the Game tab. (The one that shows when you hit "Play" to play your game in the Unity editor.) There is a dropdown under that tab to switch resolutions. I'll attach a screenshot.

Note that what options are in the dropdown will change based on your selected platform under build settings.
> 3 votes

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


title: 2D zooming in on a spot

text:
# Question
Title: 2D zooming in on a spot
The 2D library I have to work with has the following function to draw images to screen:

DrawImage(img, x, y, width, height)

Given this, I'm looking to show the entire image but then "zoom" in on a specific spot over time. I can do the over time part, but to get a zooming effect it's basically increasing the width and height, but to zoom on a specific spot on the image it seems like you have to also modify the x and y at the same time to bring that spot closer to the center of the screen. There is a relationship there that I'm not sure what it is to get the effect.

At some level it seems I should be able to write a function that zooms in on a point in the 2D image, but not sure how to go about that. Any suggestions?

# Answer
If you want to zoom into the center of the image, then the formula to get the x, y, width and height for any particular zoom level is:

```
assert zoom_level > 0
width = original_width * zoom_level
height = original_height * zoom_level
x = (original_width - width) / 2 + original_x
y = (original_height - height) / 2 + original_y

```

**Edit** If you want to zoom into point `px, py` on the original image: subtract `px * zoom_level` from x and `py * zoom_level` from y after doing the previous calculations:
> 1 votes

---
Tags: 2d
---


# Question
Title: How to get access to Nintendo Switch development environment?
I would like to make game for Nintendo Switch.

I have been searching for an SDK of the same, but I couldn't find any. The only thing I found was that I can use Unreal Engine or Unity to make games for Nintendo Switch.

However I don't want to use any of these game engines and instead want to code from scratch, making my own game engine in the process.

Isn't there a C/C++ (or any language) sdk which will allow me to make games for Nintendo Switch without using Unreal/Unity or any other game engine ?

# Answer
My understanding is that you need to register with Nintendo as a developer:

> Register for access to Nintendo developer tools and resources to create and publish games and applications for current Nintendo platforms. Resources are provided for multiple development environments including HTML5, Unity and native C++ software development.

So yes, there is a native C++ SDK. But as far as I know at the present, it's only provided by Nintendo directly.
> 3 votes

---
Tags: nintendo
---


# Question
Title: Is there any way to use events without breaking class and component separation?
I just started using events, and got stuck a little. I have a problem with the following code:

```
class InputHandler
{
      public delegate void Shooting();
      public static  event Shooting OnShoot;

      void Update()
      {
            if( fireButtonPressed)
                OnShoot();
      }
    // Rest of the class.
}

class Weapon
{
     void Shoot()
     {
         //Do the shooting.
     }

    void OnEnable()
   {
         InputHandler.OnShoot += shooting;
   }

   void OnDisable()
   {
         InputHandler.OnShoot -= shooting;
   }
}

class UI
{
     void UpdateBulletsCount(int bulletsLeft, int magSize)
     {
         //Update the UI.
     }

    void OnEnable()
   {
         InputHandler.OnShoot += UpdateBulletsCount; //  clearly can't do that.
   }

   void OnDisable()
   {
         InputHandler.OnShoot -= UpdateBulletsCount;
   }
}

```

My UI class has a method to update the bullet count when you fire, reload or change the weapon. As you can clearly see, it takes in different parameters. This allows me to change the `UpdateBulletsCount()` to accept no parameters, and find the weapons info through `GetComponent` or `Find`, in order to update `UI`.

However, then the `UI` class will depend on the `Weapon` class, which breaks the separation of classes and components that I am trying to achieve. Is there any way to use events without breaking class and component separation?

# Answer
I think the problem here is your input handler class doesn't know anything about your weapon class. Therefore you can't actually transfer information from the weapon class to the UI class. If you want to make this event driven, what you really need to is create an event that signals the UI to update when the weapon properties change. Something like...

class

```
 InputHandler
{
    void Start()
    {
        // connecting current weapon to current UI to create the pipeline
        activeWeapon.WeaponPropertiesChangedHandler += activeUI.UpdateWeaponPropertiesDisplay;
        activeWeapon.WeaponPropertiesChangedHandler += classA.UpdateWeaponPropertiesForClassA;
        activeWeapon.WeaponPropertiesChangedHandler += classB.UpdateWeaponPropertiesForClassB;
    }

    void Update()
    {
        if (fireButtonPressed)
            OnShoot();
    }
}

class Weapon
{
    public delegate void WeaponPropertiesChanged(int bulletsLeft, int magSize);
    public event WeaponPropertiesChanged WeaponPropertiesChangedHandler;

    void Shoot()
    {
        //Do the shooting.

        // Call this anytime weapon properties change (i.e. ammo, mag size, dam)
        OnWeaponPropertiesChanged();
    }

    public void OnWeaponPropertiesChanged()
    {
        // good practice to check events are assigned so won't blow up if not
        if (WeaponPropertiesChangedHandler != null)
        {
            // Call the property changed handler which is actually calling...
            WeaponPropertiesChangedHandler(bulletsLeft, magSize);
        }
    }
}

class UI
{
    // .... this function in the UI class and...
    void UpdateWeaponPropertiesDisplay(int bulletsLeft, int magSize)
    {
        //Update the UI.
    }
}

class SomeClassA
{
    // .... this function in class A and...
    void UpdateWeaponPropertiesForClassA(int bulletsLeft, int magSize)
    {
        // Update class A with weapon properties
    }
}

class SomeClassB
{
    // .... this function in class B
    void UpdateWeaponPropertiesForClassB(int bulletsLeft, int magSize)
    {
        // Update class B with weapon properties
    }
}

```

This will now give you a pipeline from weapon to UI. So now if your weapon properties change, you just need to call the OnWeaponPropertiesChanged event and pass whatever arguments you need to update the UI.

You will also have to take care with registering your events somewhere else. For example, if you change weapons, you will need to re-register the UI events and unregister the old weapons events. Since I don't know where you store this data, I made a dummy "activeWeapon" and "activeUI" variable that you will need to adjust.

Hope this helps.

Side Note: Right now there are 2 arguments being passed, if this start becomes large and cumbersome, it is a good practice to create an WeaponPropertiesChangedEventArgs Class to pass instead of the two ints.
> 2 votes

---
Tags: unity, events, delegates
---


# Question
Title: How is a gimbal connected with Euler rotation angles?
When I see any video that explains how gimbal lock occurs, they explain it using a gimbal machine and I totally understand the effect on that machine. What I don't understand is how Euler angles are related to the idea how gimbal machine works.

And my #1 confusion comes from the following:

1. Euler angles rotate the coordinate frame but the axes stay orthogonal.
2. Gimbal circles rotate so that two rotation axes become collinear.

Hence I don't understand how gimbal mechanism can show how Euler angles work.

# Answer
> 1 votes
The issue not because Euler angles can't represent all orientations (they can) but because they don't interpolate between two orientations cleanly. The analogy with the physical gimbal lock isn't 100% accurate, as your question accurately indicates, but arises due to the condition (the system is in a near-singularity state due to one of the axes being at 90 degrees). I'll try to give an example that link up how the physical and virtual models work.

Imagine being in a game in a standard FPS view where the mouse controls heading (horizontal rotation) and pitch (up/down rotation), and you are looking nearly straight up, facing north. Now, no matter how high you move the mouse, you can't actually "do a backflip" to look behind you without rotating your body 180 degrees around the heading axis (and also 180 around the roll axis (the barrel-roll axis), since your "backflip" view is upside down compared to just turning around).

Another way to think of the problem in the FPS: the game picks your roll orientation so that the top of your monitor is pointing upwards (so you're not leaning to one side). When you are facing directly up, there is no roll orientation that allows your "view up vector" to be anything other than horizontal, and mathematically you'd divide by zero if you tried to calculate the up vector from this orientation.

Now, imagine being in that same situation in a flight sim and a joystick. You're facing nearly vertical and want to "backflip" over the vertical point. Obviously the equivalent movement in the plane is to just slightly pull down on the joystick, involving none of the huge 180-degree flipping that the FPS game required. If the plane simulator simply interpolated Euler coordinates over the coordinate singularity, you'd see the plane spazz out and do some crazy 180-degree rotation between the two points. If the plane moved over the perfectly vertical mark, you'd get the same "division-by-zero" problem that we encountered in the FPS as it tried to figure out what angle to spazz through.

The equivalent analogy with the physical gymbal is if the rings are all aligned. Now, imagine trying to rotate the inner ring against the outer ring. There simply isn't a way to do it. that is gimbal lock. if all the rings are just barely unaligned though, and you try to rotate the inner ring's past the "zero mark" on the outer ring, you'd be able to rotate it, but you'd see the two inner rings do a quick 180-degree flip, just as we noticed in the FPS example when we wanted to "do the backflip".

# Answer
> 0 votes
Side note: Euler angles naturally have no rotation around the z axis, only around the x and y, Tait-Bryan angles in other hand have a z angle. I will refer to Tait-Bryan angles as Euler angles in the answer though.

The way rotations are applied to an object can cause it to first enter the Gimbal lock state by rotating it around, then when you try to apply the rotation on other axes, you won't be able to rotate it however you want. In this case the axes move around temporarily.

---
Tags: 3d, rotation, quaternion, gimbal-lock, euler-angles
---


# Question
Title: How can I get the position of a fixture in Farseer Physics 3.5?
I created a body(rectangle). After that, I attached a circle shape to the body.

I need the position(world coodinates) of the circle shape because I want to draw a circle sprite(Texture2D) on that position.

How can I get the world coodinates of the fixture?

```
Body Rectangle;
Rectangle = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
Rectangle.BodyType = BodyType.Static;
Rectangle.Position = new Vector2(4.8f, 6.4f);
Rectangle.Rotation = (float)(60 * Math.PI / 180);

CircleShape = new FarseerPhysics.Collision.Shapes.CircleShape(0.5f, 1.0f);
CircleShape.Position = new Vector2(1.0f, 0.0f);
Fixture fixture = Rectangle.CreateFixture(CircleShape, 1.0f);

```

# Answer
> -1 votes
You have to get the position of the fixture's body.

```
Vector2 position = fixture.Body.Position;

```

---
Tags: c#, xna, farseer-physics-engine
---


# Question
Title: How to add a volume bar like YouTube for iOS?
I am almost done with my game in Unity 5. However when the player presses Volume Up/Down, the iOS (version) shows the standard UI to show volume. Android has it's own (looks better on Stock).

I want to make my game consistent on either platform and different variations of Android. So I want to recreate how YouTube (for iOS) handles the change in volume.

I can't figure this out. Any help would be awesome!!!

# Answer
Unity has no functionality to take over physical volume button, especially on iOS.

Correct me if I'm wrong.
> 0 votes

---
Tags: unity, unityscript
---


# Question
Title: How to adjust the width of a LineRenderer
I wrote a code that draws a line by mouse movement. I am searching for some way to give it pencil style and head and end of the line have thinner width. As we know the LineRenderer draws the line between points. How can I access first and last point elements to set the width of them and how can I do that?

# Answer
> 3 votes
Setting the width is a different operation from setting the points. You just need to use the SetWidth(a,b) method:

```
gameObject.GetComponent<LineRenderer>().SetWidth(2.0f, 1.5f);

```

However, the width is applied over the entire line. This likely won't work very well for your simulation of a pencil line. You'd probably want to create two LineRenderers. One for most of the line, which has a consistent width from start to finish, and a second for the last segment of the line, which will have its width taper off to something small.

# Answer
> 6 votes
As of Unity 5.5 you can use an AnimationCurve.

To set only the start and end points you'd use something similar to:

```
gameObject.GetComponent<LineRenderer>().widthCurve = AnimationCurve.Linear(0, .5f, 1, .5f);

```

To set multiple points along the line to have a thinner start and end use something similar to:

```
AnimationCurve curve = new AnimationCurve();
curve.AddKey(0, 0);
curve.AddKey(.1f, .5f);
curve.AddKey(.9f, .5f);
curve.AddKey(1, 0);
gameObject.GetComponent<LineRenderer>().widthCurve = curve;

```

or this is another style of doing the same thing as above:

```
gameObject.GetComponent<LineRenderer>().widthCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(.1f, .5f), new Keyframe(.9f, .5f), new Keyframe(1, 0));

```

---
Tags: unity
---