Unity中保存或读取数组的方法

Unity本身有PlayerPrefs来做一些数据的保存和读取,也可以通过循环来做批量的读取或者保存,下面这个脚本可以方便的调用用来做上面批量的工作,比如读取一组文本数组数据和保存一组文本数组数据.

建议把这个脚本放在Standard Assets目录下,这样可以按照下面的方法方便的调用它.现在包含了下面这些命令:

  • PlayerPrefsX.SetVector3
    PlayerPrefsX.GetVector3
    PlayerPrefsX.SetIntArray
    PlayerPrefsX.GetIntArray
    PlayerPrefsX.SetFloatArray
    PlayerPrefsX.GetFloatArray
    PlayerPrefsX.SetStringArray
    PlayerPrefsX.GetStringArray

保存一个向量
static function SetVector3 (key : string, value : Vector3) : boolean
//尝试保存一个物体位置
var player : GameObject;
if (!PlayerPrefsX.SetVector3("PlayerPosition", player.transform.position))
print("不能保存物体位置!");

成功返回真,否则假(例如用Webplayer保存超过1M数据的时候).

获得一个向量
var player : GameObject;
player.transform.position = PlayerPrefsX.GetVector3("PlayerPosition");

如果读取的向量存在的话将会返回这个向量值.

保存一组整型数据
//当保存Scores命名的分数时候创建一个10成员数组
var myScores = new int[10];
for (i = 0; i < myScores.Length; i++)
    myScores[i] = i+1;
if (!PlayerPrefsX.SetIntArray("Scores", myScores))
print("不能保存分数!");

获得一组整型数据
static function GetIntArray (key : string) : int[]
如果存在将返回这组数据,否则将返回int[0];
var scores = PlayerPrefsX.GetIntArray("Scores");
static function GetIntArray (key : string, defaultValue : int, defaultSize : int) : int[]
如果不存在这组数据,将返回指定长度的数组以及每个成员都会赋予默认值.

其他函数的使用方法:
static function SetFloatArray (key : string, value : float[]) : boolean
static function GetFloatArray (key : string) : float[]
static function GetFloatArray (key : string, defaultValue : float, defaultSize : int) : float[]
static function SetStringArray (key : string, value : String[]) : boolean
static function SetStringArray (key : string, value : String[], separator : char) : boolean
static function GetStringArray (key : string) : string[]
static function GetStringArray (key : string, separator : char) : string[]
static function GetStringArray (key : string, defaultValue : String, defaultSize : int) : string[]
static function GetStringArray (key : string, separator : char, defaultValue : String, defaultSize : int) : string[]

该脚本的Javascript版:
// Site of this script: http://www.unifycommunity.com/wiki/index.php?title=ArrayPrefs

// Created by: Eric Haines (Eric5h5)
// Contribution (Set/Get Vector3) 03/2010: Mario Madureira Fontes (fontmaster)

static function SetVector3 (key : String, vector : Vector3) : boolean {
    return SetFloatArray(key, [vector.x, vector.y, vector.z]);
}

static function GetVector3 (key : String) : Vector3 {
    var floatArray = GetFloatArray(key);
    if (floatArray.Length < 3) {
        return Vector3.zero;
    }
    return Vector3(floatArray[0], floatArray[1], floatArray[2]);
}

static function SetIntArray (key : String, intArray : int[]) : boolean {
    if (intArray.Length == 0) return false;
    
    var sb = new System.Text.StringBuilder();
    for (i = 0; i < intArray.Length-1; i++) {
        sb.Append(intArray[i]).Append("|");
    }
    sb.Append(intArray[i]);
    
    try {
        PlayerPrefs.SetString(key, sb.ToString());
    }
    catch (err) {
        return false;
    }
    return true;
}

static function GetIntArray (key : String) : int[] {
    if (PlayerPrefs.HasKey(key)) {
        var stringArray = PlayerPrefs.GetString(key).Split("|"[0]);
        var intArray = new int[stringArray.Length];
        for (i = 0; i < stringArray.Length; i++) {
            intArray[i] = parseInt(stringArray[i]);
        }
        return intArray;
    }
    return new int[0];
}

static function GetIntArray (key : String, defaultValue : int, defaultSize : int) : int[] {
    if (PlayerPrefs.HasKey(key)) {
        return GetIntArray(key);
    }
    var intArray = new int[defaultSize];
    for (i = 0; i < defaultSize; i++) {
        intArray[i] = defaultValue;
    }
    return intArray;
}

static function SetFloatArray (key : String, floatArray : float[]) : boolean {
    if (floatArray.Length == 0) return false;

    var sb = new System.Text.StringBuilder();
    for (i = 0; i < floatArray.Length-1; i++) {
        sb.Append(floatArray[i]).Append("|");
    }
    sb.Append(floatArray[i]);
    
    try {
        PlayerPrefs.SetString(key, sb.ToString());
    }
    catch (err) {
        return false;
    }
    return true;
}

static function GetFloatArray (key : String) : float[] {
    if (PlayerPrefs.HasKey(key)) {
        var stringArray = PlayerPrefs.GetString(key).Split("|"[0]);
        var floatArray = new float[stringArray.Length];
        for (i = 0; i < stringArray.Length; i++) {
            floatArray[i] = parseFloat(stringArray[i]);
        }
        return floatArray;
    }
    return new float[0];
}

static function GetFloatArray (key : String, defaultValue : float, defaultSize : int) : float[] {
    if (PlayerPrefs.HasKey(key)) {
        return GetFloatArray(key);
    }
    var floatArray = new float[defaultSize];
    for (i = 0; i < defaultSize; i++) {
        floatArray[i] = defaultValue;
    }
    return floatArray;
}

static function SetStringArray (key : String, stringArray : String[], separator : char) : boolean {
    if (stringArray.Length == 0) return false;

    try {
        PlayerPrefs.SetString(key, String.Join(separator.ToString(), stringArray));
    }
    catch (err) {
        return false;
    }
    return true;
}

static function SetStringArray (key : String, stringArray : String[]) : boolean {
    if (!SetStringArray(key, stringArray, "
"[0])) {
        return false;
    }
    return true;
}

static function GetStringArray (key : String, separator : char) : String[] {
    if (PlayerPrefs.HasKey(key)) {
        return PlayerPrefs.GetString(key).Split(separator);
    }
    return new String[0];
}

static function GetStringArray (key : String) : String[] {
    if (PlayerPrefs.HasKey(key)) {
        return PlayerPrefs.GetString(key).Split("
"[0]);
    }
    return new String[0];
}

static function GetStringArray (key : String, separator : char, defaultValue : String, defaultSize : int) : String[] {
    if (PlayerPrefs.HasKey(key)) {
        return PlayerPrefs.GetString(key).Split(separator);
    }
    var stringArray = new String[defaultSize];
    for (i = 0; i < defaultSize; i++) {
        stringArray[i] = defaultValue;
    }
    return stringArray;
}

static function GetStringArray (key : String, defaultValue : String, defaultSize : int) : String[] {
    return GetStringArray(key, "
"[0], defaultValue, defaultSize);

}

脚本的C#版
// Contribution (Created CSharp Version) 10/2010: Daniel P. Rossi (DR9885)
// Contribution (Created Bool Array) 10/2010: Daniel P. Rossi (DR9885)
// Contribution (Made functions public) 01/2011: Bren

using UnityEngine;
using System;

public static class PlayerPrefsX
{
    #region Vector 3

    /// <summary>
    /// Stores a Vector3 value into a Key
    /// </summary>
    public static bool SetVector3(string key, Vector3 vector)
    {
        return SetFloatArray(key, new float[3] { vector.x, vector.y, vector.z });
    }

    /// <summary>
    /// Finds a Vector3 value from a Key
    /// </summary>
    public static Vector3 GetVector3(string key)
    {
        float[] floatArray = GetFloatArray(key);
        if (floatArray.Length < 3)
            return Vector3.zero;
        return new Vector3(floatArray[0], floatArray[1], floatArray[2]);
    }

    #endregion

    #region Bool Array

    /// <summary>
    /// Stores a Bool Array or Multiple Parameters into a Key
    /// </summary>
    public static bool SetBoolArray(string key, params bool[] boolArray)
    {
        if (boolArray.Length == 0) return false;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < boolArray.Length - 1; i++)
            sb.Append(boolArray[i]).Append("|");
        sb.Append(boolArray[boolArray.Length - 1]);

        try { PlayerPrefs.SetString(key, sb.ToString()); }
        catch (Exception e) { return false; }
        return true;
    }

    /// <summary>
    /// Returns a Bool Array from a Key
    /// </summary>
    public static bool[] GetBoolArray(string key)
    {
        if (PlayerPrefs.HasKey(key))
        {
            string[] stringArray = PlayerPrefs.GetString(key).Split("|"[0]);
            bool[] boolArray = new bool[stringArray.Length];
            for (int i = 0; i < stringArray.Length; i++)
                boolArray[i] = Convert.ToBoolean(stringArray[i]);
            return boolArray;
        }
        return new bool[0];
    }

    /// <summary>
    /// Returns a Bool Array from a Key
    /// Note: Uses default values to initialize if no key was found
    /// </summary>
    public static bool[] GetBoolArray(string key, bool defaultValue, int defaultSize)
    {
        if (PlayerPrefs.HasKey(key))
            return GetBoolArray(key);
        bool[] boolArray = new bool[defaultSize];
        for (int i = 0; i < defaultSize; i++)
            boolArray[i] = defaultValue;
        return boolArray;
    }

    #endregion

    #region Int Array

    /// <summary>
    /// Stores a Int Array or Multiple Parameters into a Key
    /// </summary>
    public static bool SetIntArray(string key, params int[] intArray)
    {
        if (intArray.Length == 0) return false;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < intArray.Length - 1; i++)
            sb.Append(intArray[i]).Append("|");
        sb.Append(intArray[intArray.Length - 1]);

        try { PlayerPrefs.SetString(key, sb.ToString()); }
        catch (Exception e) { return false; }
        return true;
    }

    /// <summary>
    /// Returns a Int Array from a Key
    /// </summary>
    public static int[] GetIntArray(string key)
    {
        if (PlayerPrefs.HasKey(key))
        {
            string[] stringArray = PlayerPrefs.GetString(key).Split("|"[0]);
            int[] intArray = new int[stringArray.Length];
            for (int i = 0; i < stringArray.Length; i++)
                intArray[i] = Convert.ToInt32(stringArray[i]);
            return intArray;
        }
        return new int[0];
    }

    /// <summary>
    /// Returns a Int Array from a Key
    /// Note: Uses default values to initialize if no key was found
    /// </summary>
    public static int[] GetIntArray(string key, int defaultValue, int defaultSize)
    {
        if (PlayerPrefs.HasKey(key))
            return GetIntArray(key);
        int[] intArray = new int[defaultSize];
        for (int i = 0; i < defaultSize; i++)
            intArray[i] = defaultValue;
        return intArray;
    }

    #endregion

    #region Float Array

    /// <summary>
    /// Stores a Float Array or Multiple Parameters into a Key
    /// </summary>
    public static bool SetFloatArray(string key, params float[] floatArray)
    {
        if (floatArray.Length == 0) return false;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < floatArray.Length - 1; i++)
            sb.Append(floatArray[i]).Append("|");
        sb.Append(floatArray[floatArray.Length - 1]);

        try
        {
            PlayerPrefs.SetString(key, sb.ToString());
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// Returns a Float Array from a Key
    /// </summary>
    public static float[] GetFloatArray(string key)
    {
        if (PlayerPrefs.HasKey(key))
        {
            string[] stringArray = PlayerPrefs.GetString(key).Split("|"[0]);
            float[] floatArray = new float[stringArray.Length];
            for (int i = 0; i < stringArray.Length; i++)
                floatArray[i] = Convert.ToSingle(stringArray[i]);
            return floatArray;
        }
        return new float[0];
    }

    /// <summary>
    /// Returns a String Array from a Key
    /// Note: Uses default values to initialize if no key was found
    /// </summary>
    public static float[] GetFloatArray(string key, float defaultValue, int defaultSize)
    {
        if (PlayerPrefs.HasKey(key))
            return GetFloatArray(key);
        float[] floatArray = new float[defaultSize];
        for (int i = 0; i < defaultSize; i++)
            floatArray[i] = defaultValue;
        return floatArray;
    }

    #endregion

    #region String Array

    /// <summary>
    /// Stores a String Array or Multiple Parameters into a Key w/ specific char seperator
    /// </summary>
    public static bool SetStringArray(string key, char separator, params string[] stringArray)
    {
        if (stringArray.Length == 0) return false;
        try
        { PlayerPrefs.SetString(key, String.Join(separator.ToString(), stringArray)); }
        catch (Exception e)
        { return false; }
        return true;
    }

    /// <summary>
    /// Stores a Bool Array or Multiple Parameters into a Key
    /// </summary>
    public static bool SetStringArray(string key, params string[] stringArray)
    {
        if (!SetStringArray(key, "
"[0], stringArray))
            return false;
        return true;
    }

    /// <summary>
    /// Returns a String Array from a key & char seperator
    /// </summary>
    public static string[] GetStringArray(string key, char separator)
    {
        if (PlayerPrefs.HasKey(key))
            return PlayerPrefs.GetString(key).Split(separator);
        return new string[0];
    }

    /// <summary>
    /// Returns a Bool Array from a key
    /// </summary>
    public static string[] GetStringArray(string key)
    {
        if (PlayerPrefs.HasKey(key))
            return PlayerPrefs.GetString(key).Split("
"[0]);
        return new string[0];
    }

    /// <summary>
    /// Returns a String Array from a key & char seperator
    /// Note: Uses default values to initialize if no key was found
    /// </summary>
    public static string[] GetStringArray(string key, char separator, string defaultValue, int defaultSize)
    {
        if (PlayerPrefs.HasKey(key))
            return PlayerPrefs.GetString(key).Split(separator);
        string[] stringArray = new string[defaultSize];
        for (int i = 0; i < defaultSize; i++)
            stringArray[i] = defaultValue;
        return stringArray;
    }

    /// <summary>
    /// Returns a String Array from a key
    /// Note: Uses default values to initialize if no key was found
    /// </summary>
    public static String[] GetStringArray(string key, string defaultValue, int defaultSize)
    {
        return GetStringArray(key, "
"[0], defaultValue, defaultSize);
    }

    #endregion
}

转载请注明来自1Vr.Cn

Unity 3.2发布!优化性能,高端效果!

惊人的速度,令人惊艳的效果;我们自信的发布Unity3.2!
这次我们主要改进了性能,增加了新的高级效果以及修正很多Bug!

主要特点:
图像效果:新的bokeh景深效果,改进bloom和several以及其他图像效果和修正.
新的水效果:全新的水预设包含在标准资源包中,其中包括水波,自动生成海岸线和边缘的泡沫效果.
图形:改进
新水:所有新的资产组合屋水标准,其中包括波,自动生成的海岸线和更多的泡沫。
图形:主要提升了OpenGL ES 2.0的性能.(iOS/Android平台).
着色器: Added optimized/simplified versions of some shaders under “Mobile” category (VertexLit, Bumped Specular, Skybox). They work on other platforms as well, but mobiles will see biggest gains.
着色器: 移动设备优化版的BumpedSpecular着色器比3.1版本快了5.2倍(在iOS上).
着色器: Added several Unlit shaders that just display a texture with no lighting. They are the fastest textured shaders.
Debugger: Attaching the script debugger to (and detaching from) Unity and debugging-enabled players is now possible.
Profiler: you can profile standalone player builds from the Editor. This includes iOS and Android builds!
编辑器
Improvements
Profiler Improvements:
Profiler is now able to connect to players to do remote profiling.
Added profiler support for iOS runtime. Editor and iOS device should be connected to the WiFi/LAN network.
添加物理的profiler监控.
Assets -> Import Package changed into a submenu for easy access to standard packages.
Android Remote is now available on all build targets; iPhone remote is now available on all build targets on Mac OS X.
PlayerSettings script class extended to let Editor scripts control various iOS and Android build settings like stripping, target devices, etc.
Slide to scrub over AudioClip previews.
资源导入部分:
Direct import of Modo files (*.lxo). Officialy supported Modo versions are 501 and higher.
Direct import from Cinema 4D R12.
Direct import from Blender 2.55.1 and later.
更新 FBX SDK 到 2011.3.1.
Support for import of mesh instances from FBX files. Import of instances is not enabled for direct import of 3dsMax/Maya files due to limitations on FBX exporters (see Known Issues).
It is now possible to switch the scene view into bottom camera using a three-finger-swipe gesture up from the up camera on Mac OS X.
When an asset import fails, it will now show up in the project folder, allowing you to reimport it manually if you like.
Made window zooming using the magnify gesture on Mac OS X less sensitive so it is not accidentally triggered.
Handles now have Slider2D function for dragging a 3D handle in a plane, see Handles.Slider2D().
树木创建器:
Improved consistency of the editor’s “look” with other Unity editors.
“Synced” the Move/Rotate Branch/Leaf tools with the Editor Move/Rotate tools.
Cleaned up tooltip text.
Model wireframe is hidden when editting branches/leaves.
对象拾取器:
Builtin resources have been added e.g the primitive meshes, default-material, default-particle texture etc.
Previews of textures now preserve the aspect ratio of the original texture.
Added check to prevent users from overwriting their project folder when building a webplayer.
Added API EditorWindow.FocusWindowIfItsOpen.
There is now an option to show a save confirmation dialog for writing changes to serialized asset and scenes.
Added build managed dependencies verification step. It will warn when unsupported .NET assemblies get included into build.
Undo system now has a memory cap to remove undo snapshots that use a lot of memory. This stops unity from crashing when editing big terrains.
When Unity quits during a script compilation, Unity will now on next restart recompile all scripts. Scripts are now generated automatically from all scripts in the asset database, making it impossible to get scripts into a non-working state if you for example delete Library/MonoManager.asset.
Heightmap terrain painting is now a lot faster.
Fixed text overdraw on inspector drop downs.
ESC cancels search in Scene, Hierarchy & Project Views.
修正Light皮肤下对象拾取器的图标.
Mac: Dragging out a window to a secondary display now never places it too far up on the screen.
Changing GUI.skin is 10x faster in the editor and no longer clobbers the GC.
Dragging assets around inside a filtered Project view no longer moves the asset to root.
Dragging objects around inside a filtered Hierarchy view no longer unparents the game object.
Layout dropdown shows name of last selected layout. It’s also pre-filled for save layout name.
Visible layers layermask is persistent between editor sessions.
Minor Build Settings window tweaks/polish.
Window docking has been rewritten, it should now have a way better feel.
EditorWindows now get OnFocus/LostFocus messages when tabs are switched.
Fixes
Screen.width and Screen.height are now correct when entering playmode using maximizeOnPlay.
Fixed bug where undo / redo would incorrectly combine multiple undo operations into one step
Fixed bug where upgrading a project with normal maps would sometimes not mark the texture as a normal map properly in the import settings.
Fixed bug where, display of ‘Texture not yet compressed’ was not working.
Fixed issue where dragging on profiler hierarchy would change the active frame.
Fixed camera viewport handles incorrect with custom viewport rect.
Fixed crash when using null texture in Handles.DrawBezier.
Fixed camera’s orthographic state is overriden if camera’s inspector is visible.
Fixed mouse picking in editor issue.
Fixed crash when instantiating a prefab with Constant Force added in FixedUpdate.
Fixed no visual indicator when dragging textures onto materials.
Fixed model preview bitmaps need fixing for models that have an off-center pivot.
Fixed change to flare setting lost when followed by drag and drop.
Fixed the Object Picker’s ‘scene’ tab list is empty on initial display for certain object types.
Fixed warnings in the console for stats window when using networking.
Fixed dragging material in sceneview does not always update correctly (Only a Windows issue).
Fixed crash on play when using the Animation system to disable a Mesh Renderer.
Fixed foldouts eating events when clipped.
Fixed object fields not pinging when disabled.
Fixed crash when calling Material.SetPass on a null material.
Fixed crash when calling NetworkUtility.Ping repeatedly and entering / exiting playmode quickly.
Fixed ‘screencoord[1]’ error messages in some situations.
Fixed tab dragging which could either throw an error “Trying to read pixel out of bounds” or show contents of another window.
Fixed wrong material previews if Player Settings has VertexLit rendering path.
Fixed a bug in Mac OS X Editor where assets with unicode characters in their file name would get converted to lower case names.
Previews in the Object Picker are now correct for dirty assets.
Fix crash when validating MeshRenderer context menu when there are no materials.
Fixed broken image references in script reference.
Fix errors when focusing on terrain with the hierarchy view.
CustomEditor bug made script-file become unusable in editor.
MenuItem with negative priorities are now working correctly.
Fixed texture importer was doing mipmap fade for normal maps wrong.
Fix sceneview sometimes losing input when a sceneview overlay window was showing (e.g. Camera Preview).
Fix Build and Run not working in Mac OS X 10.5.
Windows editor doesn’t require MS Runtime libs (9.0) to be installed.
Fixed rendering issues on Windows with Intel GMA 950/3100 GPUs in Animation, Profiler and Terrain windows.
Editor Windows stay on-screen in a much more robust fashion.
Fixed confusing Shader Model 3.0 graphics emulation (it was sometimes disabled on capable GPUs).
Fixed issue with Static Batching not working after Additive Level Load.
QuickTime movie importing now works with the latest version (7.6.9).
Fixed occasional crashes on Windows when closing Asset Store window.
Fixed Asset Store window minimum size being too large for small screen resolutions.
Switching graphics emulation properly reloads all textures now (lightmaps could get wrong encoding before in some cases).
Fixed that ProjectSettings->Editor was only available in pro, while it contained nonpro security emulation settings.
Fixed inspector enum popups being wrong for fields that have same names but different enum types on same component.
Fixed crash when using CustomEditor Attribute on a class not derived from Editor.
MonoBehaviour.Update is now correctly called in batch mode in the editor.
Fixed bug where prefab instances could lose the prefab overrides on mono behaviours when new properties were added in some corner case scenarios.
Fixed clicking behaviour while renaming in Hierarchy & Project View (sometimes Unity would not apply the new name).
Fixed context menus not working in various Project Settings inspectors.
Fixed imposter camera showing in the hierarchy for a single frame after creation.
Fixed Tree Creator mesh not updating properly when editing value’s directly in a text field.
Fixed creating projects through command line using relative paths on windows.
When selecting font with unsupported format in inspector, display nice error box instead of crashing.
Control/Command + click in SceneView now selects game objects as well as deselects them.
Fixed: Don’t open hierarchy window for no good reason when creating e.g. Cube game object.
Remove Components -> Miscellaneous -> Tree menu item, as it does not do anything useful.
Fixed display of unicode characters in the layouts popup menu.
Mac Editor: Popup windows no longer gets sent to back when you close another popup window.
Fixed layout label issues with Vector Fields.
Dragging out windows no longer can leave a 1px white hairline on bottom and right edges.
Dragging while zoomed in on mac no longer renders the window unresizable.
Fix gear context icon for material and texture inspectors in dark skin.
Build settings properly reflect changes to moving(renaming) scenes.
Graphics
Improvements
Major performance improvements in OpenGL ES 2.0 (iOS / Android):
Much improved performance of shaders that are compiled from Cg/HLSL (e.g. Diffuse for directional light is about 2x faster on iPhone 3Gs). Now fixed/half/float types in Cg map to lowp/mediump/highp precision in GLSL. Use lowest precision type in your shaders!
Improved GLSL shader optimizer.
Changed normal map compression approach for mobile platforms. It’s much faster now!
Fog mode can be changed in Render Settings (also from scripts): Linear, Exp, Exp2 (default).
Rendering performance optimizations (lower CPU overhead, less memory consumption).
Shadows:
Forward rendering path supports Point & Spot light shadows again, as well as multiple shadowing lights! Note that by default shaders do not have this enabled, use fullforwardshadows surface shader directive to enable the behavior.
Directional Light soft shadows blur width and fadeout speed can be adjusted in Inspector or via script.
Exposed Light.shadowBias to scripting.
Built-in shaders that perform Deferred Lighting, directional light shadow gathering in Deferred Lighting, and directional light shadow blurring can be overriden. Just drop your own shaders with the same names into the project.
Deferred light buffer can be accessed from from Image Effects or other shaders (_LightBuffer).
Surface Shader improvements:
support world-space normal as input (worldNormal).
fullforwardshadows directive to enable all shadows from any lights in forward rendering loop.
dualforward directive to enable dual lightmaps in Forward rendering.
decal:blend mode for shaders used on decal-like surfaces.
nolightmap directive to exclude lightmap support (makes shaders smaller).
noambient directive to not apply ambient nor SH lighting.
halfasview directive to compute normalized half-direction per-vertex, and pass that to the lighting function. Results in faster Specular-type shaders, however view direction won’t be entirely correct.
approxview directive to compute normalized view direction per-vertex instead of per-pixel. Results in faster Specular-type shaders, however view direction won’t be entirely correct when camera gets close to surface.
noforwardadd directive to skip generating forward additive pass. Will make a shader support one full directional light; all other lights will be per-vertex/SH.
Shaders: #pragma glsl_no_auto_normalization directive to not auto-normalize normals & tangents in OpenGL ES 2.0 shaders.
Shaders: Added TransformViewToProjection to do this properly on mobile devices with regard to orientation (on non-mobile it will be usual multiplication by diagonal terms of projection matrix).
Shaders: Added per vertex lit tree shaders previously used in the Bootcamp demo. To be used with Tree Creator trees and located in “Nature/Tree Creator Leaves Fast”.
Desktop GLSL shaders now allow OpenGL ES precision types to be used.
Added GL.GetGPUProjectionMatrix that returns actual projection matrix that will be used in shaders.
Added support for 16bit RenderTextures.
Scaled meshes are now only recreated if the scale has actually changed. This improves performance hiccups on same games.
Texture2D.GetPixel and friends work on RGBA32 textures (common case for uncompressed textures on mobile platforms) in addition to ARGB32 ones.
Texture2D.Apply and Texture2D.PackTextures now have additional parameter makeNoLongerReadable (default to false) that will mark Texture as not Readable, and free up system memory after uploading to GPU.
Fixes
Shaders: Bunch of fixes to Cg->GLSL shader translator:
Translates ‘half’ and ‘fixed’ matrix types properly (previously ‘half’ was translated to high precision, and ‘fixed’ was not supported).
Support lit() built-in function.
Fixes to swizzles on floats.
Support static qualifier.
Better handling of 2D matrix indexing, e.g. matrix[j].
Shaders: fixed mis-compilation of matrix constructors & matrix indexing when translating shaders to GLSL.
Shaders: fixed mis-compilation of modf() and fmod() when translating shaders to GLSL.
Shaders: Postprocess Direct3D pixel shaders that come close to 64 instruction limit to work around a crash on Intel GMA 950.
Shaders: Fix some bogus error messages when loading Direct3D shaders.
Surface Shaders: in case of syntax errors, proper line numbers are reported now… how cool is that? 😉
Surface Shaders: support #pragma multi_compile directives properly.
Lightmapper fixes:
Fixed UV layer creation for Beast. Fixes all the “Duplicate uv layer name” errors.
Fixed tiling and offset being ignored for _MainTex on objects using a non-white color.
Fixed an issue in Beast causing black areas surrounded by white outlines to sometimes appear in lightmaps.
Fixed lightmapping of objects with mirrored (odd-negative) scale.
Fixed the crash when lightmapping terrains where the Terrain script references a missing TerrainData asset.
Fixed an issue with Beast occasionally cancelling the bake process (especially on Mac OS X, but also causing poor performance on Win) when using a lot of memory.
Fixed the issue with 4096 size terrain lightmaps not baking on Mac OS X.
Fixed DXT5 alpha channel decompression to better match what GPUs are actually doing.
Fixed Texture2D.GetPixel on Alpha8 format returning 0.00392 in RGB channels instead of 1.0.
Fixed a bug in Cloth rendering that was mostly happening on Windows with Radeon GPUs.
Fixed custom projection matrices sometimes not working properly.
Fixed inconsistent triangle count display in Game View Stats when dynamic batching is used.
Fixed creation of compressed textures at runtime.
Fixed validation of vertex/pixel shaders that use more textures than the GPU can handle.
Fix texture scale/offset not being applied when writing shaders in GLSL for desktop platforms.
Fixed editor fonts getting corrupted once RenderTextures are used on Mac OS X 10.5.x with Intel GMA 950 GPU.
Fixed Texture2D.ReadPixels on Direct3D when reading into a portion of a texture.
Fixed Soft Occlusion Tree shaders sometimes rendering overbright on Windows with GeForce FX/6/7 GPUs.
Fixed lightmapped VertexLit shader applying fog in a wrong way on old GPUs with only 1 texture unit.
Texture2D.ReadPixels properly reads from Game View when non-full aspect ratio is used.
RenderTexture.GetTemporary now always returns a texture with bilinear filtering set (previously could return with something else when returning a texture from existing texture pool).
Fixed directional light shadows in case of weird projection matrices (e.g. Refractive Water).
Make WindZones be properly affected by Time Scale.
WindZones properly affect Tree Creator trees put into terrains now.
Fixed wrong Point/Spot light attenuation on Tree Creator leaves.
Graphics.Blit does not require using Cull Off in the shader now.
Shadows can be properly cast from particles now, if you use opaque or cutout shaders on them.
Fixed changing Flare color from script not always having effect.
Opaque objects are front-to-back sorted again for performance reasons. Looks like this got lost with all batching work in Unity 3.0.
Fixed dynamic batching issues with uniformly scaled objects and vertex lighting on Direct3D.
Fixed rendering of scenes containing objects with odd-negative scale in deferred when any of the lights was casting shadows.
Fixed Deferred Lighting not respecting camera’s Don’t Clear mode.
Fixed bogus error message when a shader with an empty name has no fallback.
Fixed half-texel offset error when generating tree creator texture atlas.
OpenGL ES 2.0: Fixed Fog with semitransparent fixed function shaders.
Unity iOS
Improvements
Alpha-tested objects are drawn after fully opaque ones for performance reasons.
Implemented MSAA (Multisample anti-aliasing) support. You choose it in Quality Settings just like for other platforms.
Audio: Gapless looping of MP3s! Unity’s MP3 encoding is completely rewritten and silent frames and/or audible “pops” around the loop point is no more. Use the “Gapless loop” option in the Audio Importer to encode the MP3 for looping. Beware this stretches/resamples the sound which theoretically can affect quality.
Mobile devices now have their own quality settings (Project Settings->Quality->Default Mobile Quality).
Improved performance by using OES_vertex_array_object and EXT_discard_framebuffer extensions.
Added automated native plugin integration into Xcode project. All .m/.mm/.c/.cpp/.a files located in Assets/Plugins/iOS will be merged into Xcode project with every Unity project build.
Performance warning now shows up when deploying a project using anti-aliasing and/or more than 1 pixel light.
Use unnamed process-wide kernel semaphores instead of slower system-wide semaphores.
Added armv7 only target platform.
Added “latest” SDK option, should work only for 4.2 and later SDK.
Fixes
AOT compiler stability improved when generics are used with value types like Vector3.
Audio: Restore AudioSession without losing any state (audio will continue just where it was interrupted).
Audio: Fix audio stopping when releasing a source referencing an audio clip that is in use. This resolves audio stopping when loading a new scene.
Fixed SystemInfo.operatingSystem.
Fixed Toon Outline shaders not working on iOS with landscape orientation (update Toon Shading package).
Fixed audio not coming back after an app switch on iOS.
Fixed simulator support.
Fixed -all_load linker option support.
Fixed GUI slider + stripping problem.
Fixed problem when editor was stuck in Xcode project append mode.
Fixed animation curve stripping problem.
Fixed UnityScript and Boo Array support.
Fixed MonoProperty.GetValue for .NET 2.0 Subset profile. For full .NET 2.0 profile this feature is not supported.
Fixed freeing up audio assets after loading audio into FMOD.
Now editor will report location service as stopped instead of running.
Audio: Fixed www.audioClip streaming.
Improved micro mscorlib compatibility with stripping.
Unity Android
Improvements
Upgraded to Android OS 2.3 (Gingerbread); Editor needs the latest SDK.
Android Remote – Remote debugging tool for Android devices.
The script debugger is now enabled for Android players.
Added proper development build player, with support for profiling / debugging.
Proper device filter for devices equipped with an ARMv6 (VFP enabled) CPU.
Support for reversed landscape / portrait up-side-down screen orientation (Gingerbread and later only).
Support for extra large screens, ie tablet devices (Gingerbread and later only).
Implemented Location Service (GPS/Wifi).
Decreased the install size to the Internal Storage flash memory (currently approx. 180KB, ie ~2% of 3.1).
Audio: Gapless looping of MP3s! Unity’s MP3 encoding is completely rewritten and silent frames and/or audible “pops” around the loop point is no more. Use the “Gapless loop” option in the Audio Importer to encode the MP3 for looping. Beware this stretches/resamples the sound which theoretically can affect quality.
First draft of typeless JNI integration from scripts (C#/JS) through AndroidJavaObject / AndroidJavaClass and AndroidJNI / AndroidJNIHelper.
Added UnitySendMessage on Java side to provide callback functionality to C# / JavaScript.
WWW now uses system URL class; https://, and also jar:, is now supported.
Added Application.persistentDataPath and Application.temporaryCachePath.
Added [i]PlayerSettings / Other Settings / Force SD-Card Permission
.
Removed all Unity specific resources from /res/ folder; this will ease the integration of Java resources in Plugins.
LVL permissions are detected by usage, rather than whether PlayerSettings / LVL Public Key is filled in.
Input.inputString now also works with hardware keyboard on the devices which have one.
Added editor preference for Android SDK location.
Now have their own quality settings (Project Settings->Quality->Default Mobile Quality).
Performance warning now shows up when deploying a project using anti-aliasing and/or more than 1 pixel light.
Fixes
Fixed the tablet accelerometer bug where portrait/landscape axis were swapped.
Fixed NullPointerException race-condition in FMOD when pausing the application.
Behaviour of ‘Compress Assets on Import’ turned off is now that no textures or assets will be reimported with their platform specific override settings right away. Thus allowing for fast switching between build targets. When a build is made, all assets are ensured to have the right format. (was done in earlier builds actually).
JDK lookup now fallbacks to use the PATH if registry key is not found / valid (Windows).
Fixed: No more duplicate entries in AndroidManifest.xml.
Fixed the clip rectangle of the soft input text box not being updated properly.
Added missing Mono machine.config specification file (needed for SQL access).
Audio/Accelerometer disabled in QCAR application due to missing onResume() call.
Audio: Fixed www.audioClip streaming.
Fixed crash when the LVL key is invalid.
Fixed touch began events to always have zero Touch.deltaPos.
When tapping faster than once per frame, individual taps are no longer lost, they’re reported as taps with a separate finger ID and properly incremented tap count.
Touch.tapCount is no longer hardcoded as 1 and properly returns number of rapid taps in nearly same position.
Timestamps no longer lose data by squeezing 64-bit values through 32-bit parameters.
Audio
Improvements
FMOD 4.32.02 used across all platform/build targets.
Fallback on FMODs software mp3 decoder when Apple’s decoder (hw/soft) fails completely.
Better documentation for min-/max-distance properties.
.Play() with a delay now works on iPhone.
Streaming with WWW.audioClip now works with OggVorbis (PC/Mac/Web), MP3 (iOS/Android), WAVs (all platforms) and module files (all platforms).
Streaming with WWW.audioClip is much faster.
Stream audio from disc. Added “Stream from disc” option in the Audio Importer. Choose this to stream audio directly from disc instead of loading the entire clip into memory. This can decrease your application memory usage greatly.
Optimize the playback of compressed audio (on Android and iOS).
Fixes
AudioImporter inspector cleaned up and simplified.
Fix sounds starting when switching back to a paused editor on Windows.
Fix memory trash when encoding 8 bit wav files to MP3.
Never re-encode already encoded/compressed audio.
You can now set labels on Audio Clips.
Reverb zone’s position can now be changed runtime.
Optimized play back of uncompressed audio (wav/aiff) files with “Compressed in memory” flag checked.
Fixed min/max curve editor drawing when min/max-distance is set from script.
Fix audio inspector showing garbage for audio assets that failed to import.
Force To Mono checkbox disabled for already encoded files. It had no effect anyway.
Meta files on older audio assets not changed when upgrading.
Physics
Improvements
Tweaked Continuous Collision Detection to behave better, with objects coming to rest properly.
Allow access to cloth simulation vertices by exposing Cloth.vertices and Cloth.normals.
Added Rigidbody.constraints to allow constraining Rigidbody rotation and movement to specific axes.
Fixes
Changing the trigger flag of a collider at runtime will now also be respected by Raycasts.
OnCollisionExit messages now work when the colliders are moved apart from scripting.
Fixed SkinnedCloth crashing Unity on player resolution change.
Fixed a crash in PhysX which could occasionally occur when modifying or destroying a collider during a CCD collision.
Parenting a collider to a rigidbody at runtime will now correctly add it to the rigidbody.
Fixed a crash when destroying or deactivating a collider in OnControllerColliderHit.
Fixed editing Character Controller propteries in play mode.
Make SphereCollider vs. TerrainCollider collisions smoother.
Fixed a crash in PhysX when trying to use some oddly-shaped meshes as convex MeshColliders.
Fixed a crash when trying to set properties on an invalid SpringJoint.
Fixed wrong prototype for OnCollision* messages causing classID errors.
Fixed setting MeshCollider properties from the inspector at runtime and a related editor crash.
Collider.bounds will now return an exact bounding box for rotated capsule and sphere colliders.
Other Improvements
JavaScript Improvements:
Multidimensional arrays: int[,]
do-while statements.
final/static/internal class modifiers.
Support for nested classes, enums and interfaces.
Assembly level attributes: @assembly SomeAttribute()
Parameter attributes: function foo(@SomeAttribute bar)
Support for turning off specific pragmas on a per module basis: #pragma strict off
MonoDevelop: Improved code completion for JavaScript and Boo, especially on Windows.
Scripting Improvements:
Added OnDestroy function that is called before any MonoBehaviour will be destroyed.
Added AssetDatabase.ExportPackage and AssetDatabase.ImportPackage.
Using AddComponent(Type t) now works for components that come from dynamically loaded assemblies at runtime.
Added MovieTexture.duration.
Added Mathf.IsPowerOfTwo and NextPowerOfTwo.
Object.ToString will now return the object’s type and name.
Updated Boo to 0.9.4.9 version.
Increased reliability of destruction functions. OnDestroy and OnDisable will be called on the game object before any modifications to the game object hierarchy have occurred. Destroying of objects is now faster.
Networking: It’s now possible to remove Network.Instantiate calls from the RPC buffer by calling Network.RemoveRPCs on the first NetworkView in the instantiated object.
Caching: the caching feature is now usable by all content, with or without a special license. Unlicensed content will share a single 50 MB Cache folder.
Standalone builds: Added an option to disable writing of log files, because Apple may otherwise reject Mac App Store applications in some cases.
Standalone builds: Added watermark when running Development builds, to avoid shipping with profiling/debugging turned on.
Asset Server: explain to user why some of the selected assets in merge window cannot be merged.
Other Fixes
Fixed a potential crash when stopping a streaming movie texture while it is downloading.
Generated materials during import now have correct capitalization.
Exposed texture settings in TextureImporter class.
Fixed deadlock in some corner cases in the Instantiate function, while loading asynchronously.
Left handed mouse buttons are now correctly recognized on Windows.
Standalone Player: Fixed instability/crash when running the Windows player in batchmode.
Mac OS X Standalone: Fixed default folder access mode setup to be allowed onto the Mac App Store.
OnApplicationPause is always invoked.
Fixed “thread_stack_pcs” and “~/.wapi” Mac App Store submission problems.
Destroying a transform component is now forbidden and an error message is displaying telling the user to destroy the game object instead.
Fixed crash when passing a generic type as argument to Resources.FindObjectsOfTypeAll.
Fixed crash when passing a generic type as argument to GetComponent.
Fixed: javascript shortcircuited boolean operations that involved implicit boolean casts of operands were not short circuiting.
Fixed: javascript support for calling methods taking a variable number of arguments with an explicit array argument.
Application.LoadLevel will not destroy scene assets if they are still in use by a game object marked as DontDestroyOnLoad.
Fixed Copy, Paste and other keyboard commands in Mac OS X Standalone.
Fixed Input.mousePosition while typing in Mac OS X Standalone.
Fixed installation of Unity Web Plugin from Dashboard widgets.
Caching: Added Caching.IsVersionCached as replacement for the deprecated GetVersionFromCache.
Fixed setting the font of a TextMesh from a script (the mesh would not update previously).
Fixed a crash when creating Behaviour-derived built-in components during a FixedUpdate() call.
Web Player Fixes:
Java Applet Installer: Use custom logo and progress bar/frame like in regular web plugin.
Fixed issue with loading Meshes built with older version of Unity.
Mouse movement is properly recognized on Google Chrome.
Internet Explorer now recognizes Tab key.
Background, border and text colors are properly displayed when installing Web Player.
Google Chrome doesn’t crash when web page is refreshed multiple times in succession.
Internet Explorer doesn’t crash during Web Player installation when legacy Java version is installed.
Fix crash when webplayer encounters .NET code it thinks is illegal. VerificationException is now thrown instead.
WWW.LoadUnityWeb will now work with streamed .unity3d files.
Allow passing strings with line breaks (‘
‘) to Application.ExternalCall.
Mac: Fixed Copy&amd;Paste (and other Cmd-key equivalents).
Mac: Fixed a problem where the player could fail to update the screen in Chrome.
Mac: Fix an occasional plugin failure when trying to load Unity 2.x content.
Mac: Make cursor hiding in Google Chrome and Firefox 4 work reliably.
Mac: Fix focus issue in Firefox 4.
Mac: Fix crash when unloading plugin in Firefox 4.
Mac: Fix normal PowerPC webplayer behaving like development webplayer.
Animation Fixes:
Animations were not sampling last keyframe in Clamp and DefaultWrapMode modes.
Animations were not stopping properly when animation speed is negative.
Unity uses much less memory when importing split animations now.
Fixed leak when animation system sampled material at out of bounds material index.
ModelImporter inspector doesn’t allow to enter 0 frame split animations and ModelImporter gives error if it finds such animations.
When imported model has has multiple roots and animation doesn’t Unity will add an extra root to animation in order to unify hierarchies.
Fixed import of textures/materials from old MotionBuilder files.
Fixed Materials are not imported from all layers (fixes Fbx2010.2 imports from Cinema4D).
Fixed 3ds import crash when special characters are used in texture paths or material name.
Implemented detection and warning when Scale Compensation is used in FBX file.
Implemented detection and warning for FBX files which have keyframes at invalid times (before -100 hours).
Fixed FrameRate import from FBX 2011 plugins – previously it used to always have 30FPS when imported from FBX 2011 plugins (i.e. Maya 2011, 3dsMax 2011 and so on).
AssetServer: Fixed case where merging a conflicted file would result in a file with its last content chopped off.
Security: Remove excessive logging from socket and www security.
Security: Security check now accepts URL extensions using upper case chars.
VisualStudio/MonoDevelop integration: ignore warning about private methods not being used, since Unity users need to use that construct a lot.
MonoDevelop: Workaround network failures when detecting local editors on Mac OS X.
MonoDevelop: Incorporate improvements from MonoDevelop 2.4.2.
Mono: Merged fix for generics constraint validation.
Mono: Fixed yield when waiting for multiple coroutines.
Mono: Fixed crash when Starting empty coroutine.
MonoDevelop: Merged fixes from stable 2.4 branch.
Networking: message type 73 is now properly processed as a NAT punchthrough failed connection attempt.
Networking: Fixed proxy server issues when using Network.useProxy.
Networking: Fixed problem with using NAT punchthrough in the Editor, it didn’t work after the first time and unknown message ID errors popped up.
Networking: Fixed problem with NAT punchthrough on Windows machines related to network GUID overflows.
Networking: Fixed problem with NAT detection where Port Restricted was sometimes reported instead of Address Restricted or Full Cone.
Fixed using layers and multiple animation per layer could result in incorrect blend.
Fixed ImportNormals mode None (on FBXImporter) didn’t work it used to do the same as Calculate mode and give and an incorrect warning.
Removed/Cleaned up small leaks in WWW class.
Changes
Editor: iOS SDKs prior 4.x were removed from SDK list. New default is iOS SDK 4.2.
Implemented 3 minute timeout for import of Maya files.
Implemented detection, fix-up and a warning message for NANs in animation curves of FBX files.
Default Sync to VBL to ‘true’ in Good, Beautiful, and Fantastic Quality Settings.
Proper errors when there is another project’s library folder in the project.
Application.dataPath will work like in the web player, returning the URL of the folder containing the .unity3d file (previously it would just crash).
WindZones do not “ramp up” over time anymore.
已知问题:
When autoconnect profiler is enabled the Editor can become unresponsive after selecting Build and run for Android.
Direct Modo file import issues:
Files can not be imported from modo 401, due to a problem in Modo batch mode.
UV coordinates for some meshes are not imported correctly, due to a problem in Modo Collada plugin.
Normals for some meshes are always exported as hard edges, due to a problem in Modo Collada plugin.
Unwrap: some implementation details were changed, so you may need to rebake your lightmaps, due to UV changes.
3dsMax reference meshes are not imported correctly (FBX plugins do no export any modifications added on top of the instance), because of the bug on Autodesk side. No changes on Unity side are needed, so it will be fixed as soon as Autodesk fixes FBX plugin for 3dsMax.
Materials on instance meshes are not imported correctly – they always share the same material. This happens due to structure of FBX files, so this can’t be fixed until Autodesk makes FBX structures more suitable for instanced meshes with different materials.
Audio: Seamlessly looping clips breaks when compressed for iPhone/Android.
When duplicating a dirty asset its preview in the Object Picker is incorrect until dirty again.

原文:http://unity3d.com/unity/whats-new/unity-3.2
翻译中…..
转载请注明来自1Vr.Cn,威阿翻译!

Unity历史版本下载列表

Unity历史版本下载列表
Unity6系列最新版本:Unity 6000.0.12
Unity2023系列最新版本:Unity 2023.2.20
Unity2022系列最新版本:Unity 2022.3.39
Unity2021系列最新版本:Unity 2021.3.41
Unity2020系列最新版本:Unity 2020.3.48
Unity2019系列最新版本:Unity 2019.4.40
Unity2018系列最新版本:Unity 2018.4.36
Unity2017系列最新版本:Unity 2017.4.40
Unity5.x系列最新版本:Unity 5.6.7
Unity4.x系列最新版本:Unity 4.7.2
Unity3.x系列最新版本:Unity 3.5.7
注:最近更新在2024.07.26

继续阅读

微软官方博客揭秘Kinect工作原理

你就是控制器(You are the controller)-如果你有在关注Kinect,相信已经听过这句给力的广告词了.从《Kinect Adventures!》中手脚并用堵漏水窟窿,到Zune播放界面中挥手换歌,Kinect开创了一种更加自然的娱乐交互方式.在这篇博客文章中,我将揭秘这款体感系统背后的秘密以及它如何让开发者创造Kinect体验.而Kinect团队的项目经理Arjun Dayal则将展示如何实现通过基于手势的方式来控制Xbox Dashboard和Kinect Hub.首先,让我们从指导Kinect研发的概念原理开始.
我们生活在一个模拟的世界
传统编程基于一系列的规则:原因和结果,非黑即白,非真即假.在为输入输出数目有限的简单系统建模时,这种方式工作得挺好.拿游戏《Halo》来说吧:按A键是让士官长跳,前拨左摇杆让他向前走,前拨右摇杆让他向上看.不是A,就是B.可惜的是,我们生活的真实世界并不是如此数字化,而是模拟的.
在模拟世界中,并不是只有简单的”是”和”否”,还有”也许是/否”;不仅有”对”和”错”,还有”对/错的可能性”.让我们想象一下挥手这一简单动作的所有可能性:身体运动的幅度,环境差异,衣服质地的不同,文化差异造成的动作差异等等.你可能需要研究10的23次方这么多的可能性,显然用传统编程方式来解决这类问题是不现实的.
我们从一开始就知道必须采用一种全新的,接近于人脑工作的方式来解决这一问题.当你遇到一个人的时候,你的大脑立即将注意力集中在他身上,并根据经验辨识出他的身份.这一过程并不是通过数百层的决策树来实现,人脑就是知道.婴儿很难区分出两个人的不同,但我们通过多年的学习和训练可以在几分之一秒内做到.事实上,你也许还能蛮准确地估摸出他们的年龄、性别、心情甚至个性.这也是让我们成就为人类的原因之一.
Kinect以类似的方法被创造出来.它观察身边的世界,它注意观察你的动作.即使Kinect从来没见过你挥过手,也能很快地从它学习过的TB级数据中猜测出你所做动作的含义.
Kinect传感器
Kinect骨架追踪处理流程的核心是一个无论周围环境的光照条件如何,都可以让Kinect感知世界的CMOS红外传感器.该传感器通过黑白光谱的方式来感知环境:纯黑代表无穷远,纯白代表无穷近.黑白间的灰色地带对应物体到传感器的物理距离.它收集视野范围内的每一点,并形成一幅代表周围环境的景深图像.传感器以每秒30帧的速度生成景深图像流,实时3D地再现周围环境.如果你玩过pin point impression 3D针模玩具可能更容易理解这一技术——将你的手(或者脸,如果你愿意的话)按压在这种玩具上,就可以产生你身体某一部位的简单3D模型.

寻找移动部件
Kinect需要做的下一件事是寻找图像中较可能是人体的移动物体,就像人眼下意识地聚焦在移动物体上那样.接下来,Kinect会对景深图像进行像素级评估,来辨别人体的不同部位.同时,这一过程必须以优化的预处理来缩短响应时间.
Kinect采用分割策略来将人体从背景环境中区分出来,即从噪音中提取出有用信号.Kinect可以主动追踪最多两个玩家的全身骨架,或者被动追踪最多四名玩家的形体和位置.在这一阶段,我们为每个被追踪的玩家在景深图像中创建了所谓的分割遮罩,这是一种将背景物体(比如椅子和宠物等)剔除后的景深图像.在后面的处理流程中仅仅传送分割遮罩的部分,以减轻体感计算量.

Kinect的大脑
真正的魔术在这里发生.分割化玩家图像的每一个像素都被传送进一个辨别人体部位的机器学习系统中.随后该系统将给出了某个特定像素属于哪个身体部位的可能性.比如,一个像素有80%的几率属于脚,60%的几率属于腿,40%的几率属于胸部.看起来这时候我们就可以把几率最大的可能性当作结果,但这么做未免太过武断了.我们的做法是将所有的这些可能性输入到接下来的处理流程中并且等到最后阶段再做判断.
看了上面的介绍,你也许要问我们如何教会Kinect辨识人体部位.开发这一人工智能(被称为Exemplar(模型)系统)可不是一件轻松的事情:数以TB计的数据被输入到集群系统中来教会Kinect以像素级技术来辨认手、脚以及它看到的其他身体部位.下图就是我们用来训练和测试Exemplar的数据之一.

模型匹配:生成骨架系统
处理流程的最后一步是使用之前阶段输出的结果,根据追踪到的20个关节点来生成一幅骨架系统.Kinect会评估Exemplar输出的每一个可能的像素来确定关节点.通过这种方式Kinect能够基于充分的信息最准确地评估人体实际所处位置.另外我们在模型匹配阶段还做了一些附加输出滤镜来平滑输出以及处理闭塞关节等特殊事件.
骨架追踪系统的目标之一是为处理流程的各种输出提供一种菜单式的选择界面.游戏开发者可以选择任意的系统部件组合来开发各种游戏体验.比如,你可以仅仅使用分隔映射来制造一些惊人的华丽效果(《Your Shape: Fitness Evolved》是一个好例子).
讲到这里,我们已经描绘出一个可用于控制游戏或娱乐的完全实时的体感系统.接下来,Arjun将介绍改进的Xbox Dashboard和Kinect Hub.他将向你展示这两个用户界面如何利用景深图像流和20关节骨架系统来创造一种基于自然手势的,访问游戏、电影、音乐和其他娱乐活动的全新方式.

Kinect:技术如何最终理解你!
如今,技术在我们的日常生活中扮演着重要角色,但直到现在,技术产品在真正理解人类意图以及适应个体风格差异方面做得仍然不好.Kinect的问世让这一切有所改变.站在Kinect前,它就能知道你是谁.不仅如此,还能将你和你的爱人区别开来.当你移动时,传感器能在瞬间追踪到你.想要互动?用声音和肢体移动就可以播放电影、玩游戏、和朋友聊天等等.不需要学习任何新的控制方式,多么神奇!
前面Kinect团队项目经理Ron已经描述了Kinect传感器让Xbox实时追踪玩家动作背后的高深技术,但我们如何最佳地运用?我们的目标是让玩家尽可能自如地控制Xbox,同时让所有用户可以容易地学习并理解各种控制手势.接下来我们会更加深入地揭秘这一体感技术,并且谈谈在Kinect Hub和Dashboard中的Kinect体验.
手势:从何说起?
听到我们要设计一种手势来上下左右移动物体的时候,你也许会想:”没难度啊,把你的手移到物体上,选中然后向你想要的方向移动,搞定!”
等下,别那么自信.问问你的朋友他们是怎么想的,你可能会惊讶地发现他们的回答和你是如此的不同.是你的方式更好吗?不一定,只是对你来说更有逻辑性.人类的独特之处在于能通过多种方法来完成某一特定任务.让我们拿驾驶来做例子.如果你让100个人来模仿如何开车,你可能会得到许多答案.有些人会将两手分别握住面前的10点钟和2点钟位置,有些人可能会只用一手握住12点钟位置,有些人可能会背靠椅子坐着;同样地,模仿脚踩油门、刹车和离合器的方式也会五花八门.所有这些方式都能让我们驾驶,而技术的工作就是要能识别所有这些方式——让技术理解你!
那么,识别一个看似简单动作有多复杂呢,拿伸手做例子.当你想伸手去拿什么东西的时候,你会认为伸手的方向应该完全垂直于身体平面.但实际上由于肩膀和手臂关节的结合方式,你不可能以直线方式伸手.因此,每个人都会以略为不同的方式做出一个伸手动作,但每个人都觉得这是一个同样的伸手动作.成功的手势识别就是要理解人类动作的微妙之处,并且让技术了解这些不同.
研发Kinect这款革命性产品的过程中,我们既要战胜上述挑战还要让产品易于使用.我们所做的每个决定都是人机互动领域史无前例的,我们的工作有可能将重新定义互动娱乐技术的未来.
手势原型: 去粕取精
我们在为屏幕导航创造控制手势时,采用了很常见的方法:记录下了所有能想到的天马行空的点子,比如用脚来选择菜单神马的.当我们意识到这样的点子实在太多了的时候,我们知道需要一种更靠谱的选择方式.
我们收集并记录下所有创意,并且一一制作出原型以检验那一种更适合普通用户.和普通用户进行原型测试非常重要,我们因此学到了许多关于人体运动的信息,并用于重新调整每次新测试.人机互动的现有规则并不总是适用于在客厅进行的10英寸距离上的体感交互.通过测试我们更好地理解用户行为,比如长时间做手势时怎样才舒服,以及我们创造的控制手势集和人类自然手势是否冲突.
在测试过程中,我们的理念是”不断失败,去粕取精”,我们不断抛弃不合适的方案,保留有效方案.工程、用户研究和设计团队都充分参与到手势集的原型制作过程中,并和普通用户一起进行测试,根据所有获取到的数据来决定最佳手势.
在数月的测试、观察和研究后,我们得到了一种简单且容易理解的控制方式——悬停选择和翻页控制.悬停选择是一种容易学习、高度可靠并且可预测的机制,而翻页控制提供了一种更有触感的方式来控制屏幕内容.
让我们通过Xbox Dashboard和Kinect Hub的实现方式来更加深入地谈论这种控制模型的细节.
Kinect Hub: Kinect体验大本营!
Kinect Hub是Xbox Dashboard中的Kinect体验中心,在这里你可以用手势来访问Kinect内容.Hub的设计简单且容易理解,你可以注意到我们采用了巨大的颜色分明的项目方块,让用户轻松地找到并选择他们所想做的事.

Kinect Hub: 如何使用?
可以通过悬停选择来轻易选中Kinect Hub中的任何项目.你所要做的就是将手停在想要选择的项目方块上并等待进度圆圈计时器填满.左右手都行!
我们为屏幕上的项目方块加入了一些有趣的立体效果,当你将手在项目方块间移动时可以注意到.(注意上图手掌光标所处的项目方块有略微向内翻开的效果)

如果你想看Hub中的其他东西,在屏幕左右两侧找到翻页图标.

控制方法是将手移向翻页图标上,你会发现屏幕上的手掌光标被吸附过去,接下来你只需要按屏幕显示的方向拉动即可实现翻页.

Kinect Hub光标:如何知道谁在控制以及传感器看到了什么?
尽管同时只能有一个人控制Kinect Hub的手掌光标,但在我们收到的Beta测试反馈中有一个大问题是用户不知道谁在控制,也不知道Kinect是否能够真正看到他们正在做的动作.有些时候用户在Kinect前做动作,但却无法用手掌光标选中屏幕上的项目.还有一些时候,玩家不知道客厅的家具挡住了Kinect的视线,玩家必须对房间重新布局以改善效果.这些情况都将给用户带来极大的挫败感,因此我们决定给予用户更多的信息来解决这些问题.
我们的团队采用一种有趣的方式来解决这些问题,也就是Dashboard和Kinect Hub右下角的传感器视图功能.这一视图让用户看到实时景深视频,清楚地勾勒出玩家和房间内物体的轮廓.

当玩家挥手来控制屏幕光标的时候,你会注意到在景深视频窗口中该玩家的手会发亮,这一效果让玩家知道目前谁在控制Xbox.如果你想让旁边的人接管控制,可以让他前后挥手直至切换控制成功.
希望大家喜欢这篇揭示Kinect Hub以及体感工作原理的文章.开发这一全新的用户体验是一次奇妙之旅,看到用户开始使用这一未来的娱乐互动方式让我们激动万分.

原文:http://www.xbox.com/en-US/Live/EngineeringBlog/122910-HowYouBecometheController
转自:http://www.digg360.com/2011/01/how_you_become_the_controller/