Closest point on a line

Quick piece of code to find the closest point on a line segment from a point in 3D space: –

/// <summary>
/// Get the closest point (and distance) to line segment from a point in 3D space
/// </summary>
/// <param name="a_sourcePoint">Point that we're finding the closest point to</param>
/// <param name="a_start">Start of line segment</param>
/// <param name="a_end">End of line segment</param>
/// <returns>Closest point on the line segment and distance to the point on line from the source</returns>
public Vector3 PointOnLineSegment(Vector3 a_sourcePoint, Vector3 a_start, Vector3 a_end, out float a_length)
{
Vector3 ba = a_end - a_start;
Vector3 va = a_sourcePoint - a_start;
Vector3 w2 = va - ((ba * Vector3.Dot(va, ba)) / ba.sqrMagnitude);
Vector3 pointOnLine = a_sourcePoint - w2;

a_length = (a_sourcePoint - pointOnLine).magnitude;

return pointOnLine;
}

 

 

 

 

Advertisement

Dot Product

A simple definition of a dot product that I think works really well; “The dot product tells you what amount of one vector goes in the direction of another”

Might help someone with their understanding of what a dot product actually is

 

Unity Reading JSON Files

So, this one always seems to mess me around so I’m writing it up so I’ve got an easy reference for next time.

First we define the class we want to read the JSON into. This has to match to the format of the JSON (obviously) as it’s going to deserialize it. So, quick example might look like this: –

[Serializable]
public class ContentCollection
{
    public Content[] contents;
}

[Serializable]
public class Content
{
    public int id;
    public string stringStorage;
    public string moreStringStorage;
    public string[] arrayOfStrings;
    public bool boolStorage;
    public AnotherClass[] anotherArray;
}

[Serializable]
public class AnotherClass
{
    public int id;
    public string extraStringStorage;
}

The JSON to go with this would look something like this: –

{
    "content": [
    {
        "id": "1",
        "stringStorage": "First item",
        "moreStringStorage": "",
        "arrayOfStrings": [ "aString", "anotherString" ],
        "boolStorage": true,
        "anotherArray": [
        {
            "id": "89",
            "extraStringStorage": "something here"
        },
        {
            "id": "90",
            "extraStringStorage": ""
        }
        ]
    },
    {
        "id": "2",
        "stringStorage": "Second item",
        "moreStringStorage": "",
        "arrayOfStrings": [ "aString2", "anotherString2" ],
        "boolStorage": false,
        "anotherArray": [
        {
            "id": "91",
            "extraStringStorage": "something else here"
        },
        {
            "id": "92",
            "extraStringStorage": "some more here"
        }
        ]
    }
    ]
}

Now we read the JSON using a standard Unity JSON reader. ‘json’ in this example is just a json string of the above JSON content.

using UnityEngine;

ContentCollection content = JsonUtility.FromJson<ContentCollection>(json);

All content is read in from the json and stored in an array of ‘Content’ classes which can be easily referenced as needed.

Best to note that Unity JsonUtility does not work with arrays that are stored at the base level of the JSON. It just ignores them and causes great confusion. Multiple posts about it and there are a few wrapper classes available to solve the problem as follows: –

public class JsonHelper
{
    public static T[] GetJsonArray<T>(string json)
    {
        string newJson = "{ \"array\": " + json + "}";
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
        return wrapper.array;
    }

    [System.Serializable]
    public class Wrapper<T>
    {
        public T[] array;
    }
}

 

Hope it helps

 

 

 

 

 

 

PHP: Heredoc

Heredoc is an easy way to echo html and Javascript content without having to worry about “‘s or adding ?> <?php all over the place. A simple example is as follows:-

<?php

// Lots of PHP code goes here

$id=57;  // Store the passenger number

$string=<<<END
<span class="blah">Heading</span>
<span>
<select name="project" class="moreBlah" onchange="DoSomething($id);">
END;
echo $string;

// Lots more PHP code goes here

?>

$string will store everything until it gets to the ‘END;’. The ‘END;’ MUST be on a line on its own and must be the first thing on the line.
Also, worth noting that you can just add php variables in place without any additional formatting (see above, just stick a $id in the middle of a Heredoc and it’ll come out as the correct value)

JavaScript: Post content to a php page

So, you’re working in JavaScript and you need to pass content to a php page. On the JavaScript side, you do this: –

var formData=new FormData();
formData.append('myString', myString);

var url="./accessMyString.php";

xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.send(formData);

This will store the string (or anything else you need to pass) into ‘myString’ in the FormData and will trigger “./accessMyString.php” passing the data as a POST.

In “accessMyString.php”, you’ll read content from the POST using the usual: –

$myString = $_POST['myString'];

 

 

 

PHP: Connect to a MySQL database, run a query and read a field

Quick reference for how to read a single field from a MySQL database in PHP: –

// Connect to the database
$mysqli = new mysqli(my.server.com', 'schemaName', 'password', 'databaseName') or die ('<b>Could not connect: </b>' . mysql_error());

// Query the database for the info we need
$results = $mysqli->query("SELECT * FROM myData WHERE id='$id'") or die($mysqli->error);

$content = $results->fetch_assoc();
$field = $content['fieldName'];

 

 

JavaScript: Access element in iframe ‘A’ from iframe ‘B’

So, I’ve got an iframe called “mainiframe” and I want to access an element in “subiframe”. As long as the “subiframe” has its name set to “subiframe”, all I have to do to find the element ‘test’ is: –

var el = parent.subiframe.document.getElementById("test");

 

iOS: Change device capabilities with a postProcessBuild step

So, this one solves a bug in Unity 2017.4.2f2 that causes the armv7 device capability to be added to a 64 bit only build. We actually want arm64 instead of armv7 so I’ve setup this little hack to handle the fix

 

using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System;

// This has been added as a patch to solve a bug in Unity 2017.4.2f2 that incorrectly adds armv7 instead of arm64 to the plist
// ...and no, I don't like doing this.

public class PatchArchitecture
{
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
if (target != BuildTarget.iOS)
return;

#if UNITY_IOS

string filePath = Path.Combine(pathToBuiltProject, "Info.plist");
PlistDocument plist = new PlistDocument();
plist.ReadFromString(File.ReadAllText(filePath));
PlistElementDict rootDict = plist.root;

// Get or create array to manage device capabilities
const string capsKey = "UIRequiredDeviceCapabilities";
PlistElementArray capsArray;
PlistElement element;

capsArray = rootDict.values.TryGetValue(capsKey, out element) ? element.AsArray() : rootDict.CreateArray(capsKey);

// Remove the armv7
const string arch = "armv7";
capsArray.values.RemoveAll(x => arch.Equals(x.AsString()));

// Add the arm64
capsArray.AddString("arm64");
File.WriteAllText(filePath, plist.WriteToString());

#endif // #if UNITY_IOS
}
}


Using AJAX to handle updates to a specific entry in a list

Bit clunky as I’m in a hurry, but this is really just to remind me how to set this up when I do it next time.

So, imagine you have a list of div’s. Each div contains a visual representation of a task or a database entry that you’re showing to a user. You want to dynamically update content within each div depending on the selection made in a pulldown: –

JavaScript

The ‘onchange’ of the pulldown (select element) calls OnChange in the code below and triggers and update for the given index. sel is the select element and idIn is the index in the list of “div’s” (the 0 or 1 in “id=’div_0′”, “id=’div_1′” etc)

// ==========================================================================
// Use ajax to populate a div based on selection in a select element
// ==========================================================================
function OnChange(sel, idIn)
{
    xmlhttp = newXMLHttpRequest();
    xmlhttp.onreadystatechange = SubFunction(idIn); // Use a sub-function to handle the parameter passing

    // Pass in the selected index so we know which 'div' to replace
    var selected = sel.options[sel.selectedIndex].value;
    xmlhttp.open("GET", "./populate.php?s=" + selected, true);
    xmlhttp.send();
}

// ==========================================================================
// Handle the ajax callback
// ==========================================================================
function SubFunction(idIn)
{
    return function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            var el = document.getElementById("div_" + idIn);
            el.innerHTML = this.responseText;
        }
    };
}
PHP
<!-- populate.php would be something like... -->
<?php

// Build content based as required here. This will be inserted into the innerHTML of the appropriate div

$id = $_GET['s'];
echo "here's some content: ".$id;
?>
HTML
…and the HTML is set up quite simply as: –
$string=<<<END
    <select onchange='OnChange(this, $id)'>
        <option value="0">Option 1</option>
        <option value="1">Option 2</option>
        <option value="2">Option 3</option>
    </select>
END;
echo $string;

The $id is the id of the current row in the div list (matches the div element id)