« 包含标签 Javascript 的文章

Spin like “Google Earth” in Unity

It’s complicated than I thought…

#pragma strict
 
var numberAverages : int = 3;
private var originalRotation : Quaternion;
private var offsetRotation : Quaternion;
 
// Make sure there are always SphereCollider and Rigidbody
@script RequireComponent (SphereCollider)
@script RequireComponent (Rigidbody)
 
function Awake () {
    numberAverages = Mathf.Clamp (numberAverages, 1, numberAverages);
}
 
function OnMouseDown () {
    var hit : RaycastHit;
    var dir : Vector3;
 
    // Stop spinning
    rigidbody.angularVelocity = Vector3.zero;
 
    // Record initial variables 
    if (Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), hit)) {
        originalRotation = transform.rotation;
        dir = hit.point - transform.position;
        offsetRotation = Quaternion.Inverse (Quaternion.LookRotation (dir));
        Spin (dir);
    }
}
 
function Spin (dir : Vector3) {
    var hit : RaycastHit;
    var privDirList : Array = new Array ();
    var currentDir : Vector3;
 
    // Initialize previous direction list
    for (var i : int = 0; i < numberAverages; i++) {
        privDirList.Add (currentDir);
    }
 
    currentDir = dir;
 
    // Make the object rotate with the cursor while we are grabbing it
    while (Input.GetButton ("Fire1") && Physics.Raycast (camera.main.ScreenPointToRay(Input.mousePosition), hit)) {
        // Remove first element of the array
        privDirList.RemoveAt (0);
 
        // Add current direction to the end
        privDirList.Add (currentDir);
        currentDir = hit.point - transform.position;
        transform.rotation =  Quaternion.LookRotation (currentDir) * offsetRotation * originalRotation;
        yield;
    }
 
    // User let go of the mouse so make the object spin on its own
    var avgPrevDir : Vector3 = Vector3.zero;
    var newPDirList : Vector3[] = privDirList.ToBuiltin(Vector3);
    for (dir in newPDirList) {
        avgPrevDir += dir;
    }
 
    // Keep spinning with the direction when you end touching
    avgPrevDir /= numberAverages;
    MoveAcceleration (currentDir, avgPrevDir); 
}
 
function MoveAcceleration (r2 : Vector3, r1 : Vector3) {
    var linearVelocity : Vector3;
    var angVelocity : Vector3;
 
    // Calculate the angular velocity:  Omega = r x v / r^2
    linearVelocity = (r2 - r1) / Time.deltaTime;
    rigidbody.angularVelocity = Vector3.Cross (r2, linearVelocity) / r2.sqrMagnitude;
}

Sorting a JavaScript array using array.sort()

Sorting arrays in JavaScript is done via the method array.sort(), a method that’s probably as much misunderstood as it is underestimated. While calling sort() by itself simply sorts the array in lexicographical (aka alphabetical) order, the sky’s really the limit once you go beyond the surface.

Sorting an array in lexicographical order

Sorting an array lexicographically (aka “alphabetically” or in dictionary order) is easy to do. Just call array.sort() without any parameters passed in:

1
2
3
//Sort alphabetically and ascending:
var myarray=["Bob", "Bully", "Amy"];
myarray.sort(); //Array now becomes ["Amy", "Bob", "Bully"]

Notice that the order is ascending. To make it descending instead, the simplest way is to enlist the help of another Array method in combination, array.reverse():

1
2
3
4
//Sort alphabetically and descending:
var myarray=["Bob", "Bully", "Amy"];
myarray.sort();
myarray.reverse(); //Array now becomes ["Bully", "Bob", "Amy"]

Now, before you start feeling comfortable, consider what happens if we call array.sort() on an array consisting of numbers:

1
2
var myarray=[7, 40, 300];
myarray.sort(); //Array now becomes [300,40,7]

Although 7 is numerically smaller than 40 or 300, lexicographically, it is larger, so 7 appears at the very right of the sorted array. Remember, by default array.sort() sorts its elements in lexicographical order.

And there you have it with array.sort() in terms of its basic usage. But there’s a lot more to this method than meets the eye. Array.sort() accepts an optional parameter in the form of a function reference that pretty much lets you sort an array based on any custom criteria, such as sort an array numerically or shuffle it (randomize the order of its elements).
Passing in a function reference into array.sort()
As touched on already, array.sort() accepts an optional parameter in the form of a function reference (lets call it sortfunction). The format of this function looks like this:

1
2
3
4
5
array.sort(sortfunction);
 
function sortfunction(a, b){
    //Compare "a" and "b" in some fashion, and return -1, 0, or 1
}

When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements “a” and “b” and the function’s return value. The three possible return numbers are:0 (greater than 0):

Less than 0: Sort “a” to be a lower index than “b”
Zero: “a” and “b” should be considered equal, and no sorting performed.
Greater than 0: Sort “b” to be a lower index than “a”.

To sort an array numerically and ascending for example, the body of your function would look like this:

1
2
3
function sortfunction(a, b){
    return (a - b); //causes an array to be sorted numerically and ascending
}

More on this below.
Sorting an array in numerical order

To sort an array in numerical order, simply pass a custom sortfunction into array.sort() that returns the difference between “a” and “b”, the two parameters indirectly/ automatically fed into the function:

1
2
3
//Sort numerically and ascending:
var myarray=[25, 8, 7, 41];
myarray.sort(function(a,b){return a - b}); //Array now becomes [7, 8, 25, 41]

This works the way it does because whenever “a” is less than “b”, a negative value is returned, which results in the smaller elements always appearing to the left of the larger ones, in other words, ascending.

Sort an array numerically but descending isn’t much different, and just requires reversing the two operands “a” and “b”:

1
2
3
//Sort numerically and descending:
var myarray=[25, 8, 7, 41];
myarray.sort(function(a,b){return b - a}) ;//Array now becomes [41, 25, 8, 71]

Shuffling (randomizing) the order of an array

To randomize the order of the elements within an array, what we need is the body of our sortfunction to return a number that is randomly0, irrespective to the relationship between “a” and “b”. The below will do the trick:

1
2
3
//Randomize the order of the array:
var myarray=[25, 8, "George", "John"];
myarray.sort(function() {return 0.5 - Math.random()}); //Array elements now scrambled

As you can see, there is a lot more to array.sort() than many may think. In fact, you can even sort arrays that contain more than just primitive values, but objects with properties. Lets see that next.