code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
// Copyright (c) 2011 Bob Berkebile (pixelplacment)
// Please direct any bugs/comments/suggestions to http://pixelplacement.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/*
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright (c)2001 Robert Penner
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#region Namespaces
using System;
using System.Collections;
using System.Reflection;
using UnityEngine;
#endregion
/// <summary>
/// <para>Version: 2.0.45</para>
/// <para>Author: Bob Berkebile (http://pixelplacement.com)</para>
/// <para>Support: http://itween.pixelplacement.com</para>
/// </summary>
public class iTween : MonoBehaviour{
#region Variables
//repository of all living iTweens:
public static ArrayList tweens = new ArrayList();
//camera fade object:
private static GameObject cameraFade;
//status members (made public for visual troubleshooting in the inspector):
public string id, type, method;
public iTween.EaseType easeType;
public float time, delay;
public LoopType loopType;
public bool isRunning,isPaused;
/* GFX47 MOD START */
public string _name;
/* GFX47 MOD END */
//private members:
private float runningTime, percentage;
private float delayStarted; //probably not neccesary that this be protected but it shuts Unity's compiler up about this being "never used"
private bool kinematic, isLocal, loop, reverse, wasPaused, physics;
private Hashtable tweenArguments;
private Space space;
private delegate float EasingFunction(float start, float end, float value);
private delegate void ApplyTween();
private EasingFunction ease;
private ApplyTween apply;
private AudioSource audioSource;
private Vector3[] vector3s;
private Vector2[] vector2s;
private Color[,] colors;
private float[] floats;
private Rect[] rects;
private CRSpline path;
private Vector3 preUpdate;
private Vector3 postUpdate;
private NamedValueColor namedcolorvalue;
private float lastRealTime; // Added by PressPlay
private bool useRealTime; // Added by PressPlay
/// <summary>
/// The type of easing to use based on Robert Penner's open source easing equations (http://www.robertpenner.com/easing_terms_of_use.html).
/// </summary>
public enum EaseType{
easeInQuad,
easeOutQuad,
easeInOutQuad,
easeInCubic,
easeOutCubic,
easeInOutCubic,
easeInQuart,
easeOutQuart,
easeInOutQuart,
easeInQuint,
easeOutQuint,
easeInOutQuint,
easeInSine,
easeOutSine,
easeInOutSine,
easeInExpo,
easeOutExpo,
easeInOutExpo,
easeInCirc,
easeOutCirc,
easeInOutCirc,
linear,
spring,
/* GFX47 MOD START */
//bounce,
easeInBounce,
easeOutBounce,
easeInOutBounce,
/* GFX47 MOD END */
easeInBack,
easeOutBack,
easeInOutBack,
/* GFX47 MOD START */
//elastic,
easeInElastic,
easeOutElastic,
easeInOutElastic,
/* GFX47 MOD END */
punch
}
/// <summary>
/// The type of loop (if any) to use.
/// </summary>
public enum LoopType{
/// <summary>
/// Do not loop.
/// </summary>
none,
/// <summary>
/// Rewind and replay.
/// </summary>
loop,
/// <summary>
/// Ping pong the animation back and forth.
/// </summary>
pingPong
}
/// <summary>
/// Many shaders use more than one color. Use can have iTween's Color methods operate on them by name.
/// </summary>
public enum NamedValueColor{
/// <summary>
/// The main color of a material. Used by default and not required for Color methods to work in iTween.
/// </summary>
_Color,
/// <summary>
/// The specular color of a material (used in specular/glossy/vertexlit shaders).
/// </summary>
_SpecColor,
/// <summary>
/// The emissive color of a material (used in vertexlit shaders).
/// </summary>
_Emission,
/// <summary>
/// The reflection color of the material (used in reflective shaders).
/// </summary>
_ReflectColor
}
#endregion
#region Defaults
/// <summary>
/// A collection of baseline presets that iTween needs and utilizes if certain parameters are not provided.
/// </summary>
public static class Defaults{
//general defaults:
public static float time = 1f;
public static float delay = 0f;
public static NamedValueColor namedColorValue = NamedValueColor._Color;
public static LoopType loopType = LoopType.none;
public static EaseType easeType = iTween.EaseType.easeOutExpo;
public static float lookSpeed = 3f;
public static bool isLocal = false;
public static Space space = Space.Self;
public static bool orientToPath = false;
public static Color color = Color.white;
//update defaults:
public static float updateTimePercentage = .05f;
public static float updateTime = 1f*updateTimePercentage;
//cameraFade defaults:
public static int cameraFadeDepth = 999999;
//path look ahead amount:
public static float lookAhead = .05f;
public static bool useRealTime = false; // Added by PressPlay
//look direction:
public static Vector3 up = Vector3.up;
}
#endregion
#region #1 Static Registers
/// <summary>
/// Sets up a GameObject to avoid hiccups when an initial iTween is added. It's advisable to run this on every object you intend to run iTween on in its Start or Awake.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target to be initialized for iTween.
/// </param>
public static void Init(GameObject target){
MoveBy(target,Vector3.zero,0);
}
/// <summary>
/// Instantly changes the amount(transparency) of a camera fade and then returns it back over time with MINIMUM customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for how transparent the Texture2D that the camera fade uses is.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void CameraFadeFrom(float amount, float time){
if(cameraFade){
CameraFadeFrom(Hash("amount",amount,"time",time));
}else{
Debug.LogError("iTween Error: You must first add a camera fade object with CameraFadeAdd() before atttempting to use camera fading.");
}
}
/// <summary>
/// Instantly changes the amount(transparency) of a camera fade and then returns it back over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for how transparent the Texture2D that the camera fade uses is.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void CameraFadeFrom(Hashtable args){
//establish iTween:
if(cameraFade){
ColorFrom(cameraFade,args);
}else{
Debug.LogError("iTween Error: You must first add a camera fade object with CameraFadeAdd() before atttempting to use camera fading.");
}
}
/// <summary>
/// Changes the amount(transparency) of a camera fade over time with MINIMUM customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for how transparent the Texture2D that the camera fade uses is.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void CameraFadeTo(float amount, float time){
if(cameraFade){
CameraFadeTo(Hash("amount",amount,"time",time));
}else{
Debug.LogError("iTween Error: You must first add a camera fade object with CameraFadeAdd() before atttempting to use camera fading.");
}
}
/// <summary>
/// Changes the amount(transparency) of a camera fade over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for how transparent the Texture2D that the camera fade uses is.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void CameraFadeTo(Hashtable args){
/*
CameraFadeAdd(Defaults.cameraFadeDepth);
//rescale cameraFade just in case screen size has changed to ensure it takes up the full screen:
cameraFade.guiTexture.pixelInset=new Rect(0,0,Screen.width,Screen.height);
*/
if(cameraFade){
//establish iTween:
ColorTo(cameraFade,args);
}else{
Debug.LogError("iTween Error: You must first add a camera fade object with CameraFadeAdd() before atttempting to use camera fading.");
}
}
/// <summary>
/// Returns a value to an 'oncallback' method interpolated between the supplied 'from' and 'to' values for application as desired. Requires an 'onupdate' callback that accepts the same type as the supplied 'from' and 'to' properties.
/// </summary>
/// <param name="from">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> or <see cref="Vector3"/> or <see cref="Vector2"/> or <see cref="Color"/> or <see cref="Rect"/> for the starting value.
/// </param>
/// <param name="to">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> or <see cref="Vector3"/> or <see cref="Vector2"/> or <see cref="Color"/> or <see cref="Rect"/> for the ending value.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed (only works with Vector2, Vector3, and Floats)
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ValueTo(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
if (!args.Contains("onupdate") || !args.Contains("from") || !args.Contains("to")) {
Debug.LogError("iTween Error: ValueTo() requires an 'onupdate' callback function and a 'from' and 'to' property. The supplied 'onupdate' callback must accept a single argument that is the same type as the supplied 'from' and 'to' properties!");
return;
}else{
//establish iTween:
args["type"]="value";
if (args["from"].GetType() == typeof(Vector2)) {
args["method"]="vector2";
}else if (args["from"].GetType() == typeof(Vector3)) {
args["method"]="vector3";
}else if (args["from"].GetType() == typeof(Rect)) {
args["method"]="rect";
}else if (args["from"].GetType() == typeof(Single)) {
args["method"]="float";
}else if (args["from"].GetType() == typeof(Color)) {
args["method"]="color";
}else{
Debug.LogError("iTween Error: ValueTo() only works with interpolating Vector3s, Vector2s, floats, ints, Rects and Colors!");
return;
}
//set a default easeType of linear if none is supplied since eased color interpolation is nearly unrecognizable:
if (!args.Contains("easetype")) {
args.Add("easetype",EaseType.linear);
}
Launch(target,args);
}
}
/// <summary>
/// Changes a GameObject's alpha value instantly then returns it to the provided alpha over time with MINIMUM customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation. Identical to using ColorFrom and using the "a" parameter.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="alpha">
/// A <see cref="System.Single"/> for the final alpha value of the animation.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void FadeFrom(GameObject target, float alpha, float time){
FadeFrom(target,Hash("alpha",alpha,"time",time));
}
/// <summary>
/// Changes a GameObject's alpha value instantly then returns it to the provided alpha over time with FULL customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation. Identical to using ColorFrom and using the "a" parameter.
/// </summary>
/// <param name="alpha">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the initial alpha value of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the initial alpha value of the animation.
/// </param>
/// <param name="includechildren">
/// A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void FadeFrom(GameObject target, Hashtable args){
ColorFrom(target,args);
}
/// <summary>
/// Changes a GameObject's alpha value over time with MINIMUM customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation. Identical to using ColorTo and using the "a" parameter.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="alpha">
/// A <see cref="System.Single"/> for the final alpha value of the animation.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void FadeTo(GameObject target, float alpha, float time){
FadeTo(target,Hash("alpha",alpha,"time",time));
}
/// <summary>
/// Changes a GameObject's alpha value over time with FULL customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation. Identical to using ColorTo and using the "a" parameter.
/// </summary>
/// <param name="alpha">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the final alpha value of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the final alpha value of the animation.
/// </param>
/// <param name="includechildren">
/// A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void FadeTo(GameObject target, Hashtable args){
ColorTo(target,args);
}
/// <summary>
/// Changes a GameObject's color values instantly then returns them to the provided properties over time with MINIMUM customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="color">
/// A <see cref="Color"/> to change the GameObject's color to.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ColorFrom(GameObject target, Color color, float time){
ColorFrom(target,Hash("color",color,"time",time));
}
/// <summary>
/// Changes a GameObject's color values instantly then returns them to the provided properties over time with FULL customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation.
/// </summary>
/// <param name="color">
/// A <see cref="Color"/> to change the GameObject's color to.
/// </param>
/// <param name="r">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color red.
/// </param>
/// <param name="g">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
/// </param>
/// <param name="b">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
/// </param>
/// <param name="a">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the alpha.
/// </param>
/// <param name="namedcolorvalue">
/// A <see cref="NamedColorValue"/> or <see cref="System.String"/> for the individual setting of the alpha.
/// </param>
/// <param name="includechildren">
/// A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ColorFrom(GameObject target, Hashtable args){
Color fromColor = new Color();
Color tempColor = new Color();
//clean args:
args = iTween.CleanArgs(args);
//handle children:
if(!args.Contains("includechildren") || (bool)args["includechildren"]){
foreach(Transform child in target.transform){
Hashtable argsCopy = (Hashtable)args.Clone();
argsCopy["ischild"]=true;
ColorFrom(child.gameObject,argsCopy);
}
}
//set a default easeType of linear if none is supplied since eased color interpolation is nearly unrecognizable:
if (!args.Contains("easetype")) {
args.Add("easetype",EaseType.linear);
}
//set tempColor and base fromColor:
if(target.GetComponent(typeof(GUITexture))){
tempColor=fromColor=target.guiTexture.color;
}else if(target.GetComponent(typeof(GUIText))){
tempColor=fromColor=target.guiText.material.color;
}else if(target.renderer){
tempColor=fromColor=target.renderer.material.color;
}else if(target.light){
tempColor=fromColor=target.light.color;
}
//set augmented fromColor:
if(args.Contains("color")){
fromColor=(Color)args["color"];
}else{
if (args.Contains("r")) {
fromColor.r=(float)args["r"];
}
if (args.Contains("g")) {
fromColor.g=(float)args["g"];
}
if (args.Contains("b")) {
fromColor.b=(float)args["b"];
}
if (args.Contains("a")) {
fromColor.a=(float)args["a"];
}
}
//alpha or amount?
if(args.Contains("amount")){
fromColor.a=(float)args["amount"];
args.Remove("amount");
}else if(args.Contains("alpha")){
fromColor.a=(float)args["alpha"];
args.Remove("alpha");
}
//apply fromColor:
if(target.GetComponent(typeof(GUITexture))){
target.guiTexture.color=fromColor;
}else if(target.GetComponent(typeof(GUIText))){
target.guiText.material.color=fromColor;
}else if(target.renderer){
target.renderer.material.color=fromColor;
}else if(target.light){
target.light.color=fromColor;
}
//set new color arg:
args["color"]=tempColor;
//establish iTween:
args["type"]="color";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Changes a GameObject's color values over time with MINIMUM customization options. If a GUIText or GUITexture component is attached, they will become the target of the animation.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="color">
/// A <see cref="Color"/> to change the GameObject's color to.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ColorTo(GameObject target, Color color, float time){
ColorTo(target,Hash("color",color,"time",time));
}
/// <summary>
/// Changes a GameObject's color values over time with FULL customization options. If a GUIText or GUITexture component is attached, they will become the target of the animation.
/// </summary>
/// <param name="color">
/// A <see cref="Color"/> to change the GameObject's color to.
/// </param>
/// <param name="r">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color red.
/// </param>
/// <param name="g">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
/// </param>
/// <param name="b">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
/// </param>
/// <param name="a">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the alpha.
/// </param>
/// <param name="namedcolorvalue">
/// A <see cref="NamedColorValue"/> or <see cref="System.String"/> for the individual setting of the alpha.
/// </param>
/// <param name="includechildren">
/// A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ColorTo(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//handle children:
if(!args.Contains("includechildren") || (bool)args["includechildren"]){
foreach(Transform child in target.transform){
Hashtable argsCopy = (Hashtable)args.Clone();
argsCopy["ischild"]=true;
ColorTo(child.gameObject,argsCopy);
}
}
//set a default easeType of linear if none is supplied since eased color interpolation is nearly unrecognizable:
if (!args.Contains("easetype")) {
args.Add("easetype",EaseType.linear);
}
//establish iTween:
args["type"]="color";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Instantly changes an AudioSource's volume and pitch then returns it to it's starting volume and pitch over time with MINIMUM customization options. Default AudioSource attached to GameObject will be used (if one exists) if not supplied.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation which holds the AudioSource to be changed.
/// </param>
/// <param name="volume"> for the target level of volume.
/// A <see cref="System.Single"/>
/// </param>
/// <param name="pitch"> for the target pitch.
/// A <see cref="System.Single"/>
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void AudioFrom(GameObject target, float volume, float pitch, float time){
AudioFrom(target,Hash("volume",volume,"pitch",pitch,"time",time));
}
/// <summary>
/// Instantly changes an AudioSource's volume and pitch then returns it to it's starting volume and pitch over time with FULL customization options. Default AudioSource attached to GameObject will be used (if one exists) if not supplied.
/// </summary>
/// <param name="audiosource">
/// A <see cref="AudioSource"/> for which AudioSource to use.
/// </param>
/// <param name="volume">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the target level of volume.
/// </param>
/// <param name="pitch">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the target pitch.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void AudioFrom(GameObject target, Hashtable args){
Vector2 tempAudioProperties;
Vector2 fromAudioProperties;
AudioSource tempAudioSource;
//clean args:
args = iTween.CleanArgs(args);
//set tempAudioSource:
if(args.Contains("audiosource")){
tempAudioSource=(AudioSource)args["audiosource"];
}else{
if(target.GetComponent(typeof(AudioSource))){
tempAudioSource=target.audio;
}else{
//throw error if no AudioSource is available:
Debug.LogError("iTween Error: AudioFrom requires an AudioSource.");
return;
}
}
//set tempAudioProperties:
tempAudioProperties.x=fromAudioProperties.x=tempAudioSource.volume;
tempAudioProperties.y=fromAudioProperties.y=tempAudioSource.pitch;
//set augmented fromAudioProperties:
if(args.Contains("volume")){
fromAudioProperties.x=(float)args["volume"];
}
if(args.Contains("pitch")){
fromAudioProperties.y=(float)args["pitch"];
}
//apply fromAudioProperties:
tempAudioSource.volume=fromAudioProperties.x;
tempAudioSource.pitch=fromAudioProperties.y;
//set new volume and pitch args:
args["volume"]=tempAudioProperties.x;
args["pitch"]=tempAudioProperties.y;
//set a default easeType of linear if none is supplied since eased audio interpolation is nearly unrecognizable:
if (!args.Contains("easetype")) {
args.Add("easetype",EaseType.linear);
}
//establish iTween:
args["type"]="audio";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Fades volume and pitch of an AudioSource with MINIMUM customization options. Default AudioSource attached to GameObject will be used (if one exists) if not supplied.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation which holds the AudioSource to be changed.
/// </param>
/// <param name="volume"> for the target level of volume.
/// A <see cref="System.Single"/>
/// </param>
/// <param name="pitch"> for the target pitch.
/// A <see cref="System.Single"/>
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void AudioTo(GameObject target, float volume, float pitch, float time){
AudioTo(target,Hash("volume",volume,"pitch",pitch,"time",time));
}
/// <summary>
/// Fades volume and pitch of an AudioSource with FULL customization options. Default AudioSource attached to GameObject will be used (if one exists) if not supplied.
/// </summary>
/// <param name="audiosource">
/// A <see cref="AudioSource"/> for which AudioSource to use.
/// </param>
/// <param name="volume">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the target level of volume.
/// </param>
/// <param name="pitch">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the target pitch.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void AudioTo(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//set a default easeType of linear if none is supplied since eased audio interpolation is nearly unrecognizable:
if (!args.Contains("easetype")) {
args.Add("easetype",EaseType.linear);
}
//establish iTween:
args["type"]="audio";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Plays an AudioClip once based on supplied volume and pitch and following any delay with MINIMUM customization options. AudioSource is optional as iTween will provide one.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation which holds the AudioSource to be utilized.
/// </param>
/// <param name="audioclip">
/// A <see cref="AudioClip"/> for a reference to the AudioClip to be played.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> for the time in seconds the action will wait before beginning.
/// </param>
public static void Stab(GameObject target, AudioClip audioclip, float delay){
Stab(target,Hash("audioclip",audioclip,"delay",delay));
}
/// <summary>
/// Plays an AudioClip once based on supplied volume and pitch and following any delay with FULL customization options. AudioSource is optional as iTween will provide one.
/// </summary>
/// <param name="audioclip">
/// A <see cref="AudioClip"/> for a reference to the AudioClip to be played.
/// </param>
/// <param name="audiosource">
/// A <see cref="AudioSource"/> for which AudioSource to use
/// </param>
/// <param name="volume">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the target level of volume.
/// </param>
/// <param name="pitch">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the target pitch.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the action will wait before beginning.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void Stab(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween:
args["type"]="stab";
Launch(target,args);
}
/// <summary>
/// Instantly rotates a GameObject to look at the supplied Vector3 then returns it to it's starting rotation over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> to be the Vector3 that the target will look towards.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void LookFrom(GameObject target, Vector3 looktarget, float time){
LookFrom(target,Hash("looktarget",looktarget,"time",time));
}
/// <summary>
/// Instantly rotates a GameObject to look at a supplied Transform or Vector3 then returns it to it's starting rotation over time with FULL customization options.
/// </summary>
/// <param name="looktarget">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for a target the GameObject will look at.
/// </param>
/// <param name="axis">
/// A <see cref="System.String"/>. Restricts rotation to the supplied axis only.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void LookFrom(GameObject target, Hashtable args){
Vector3 tempRotation;
Vector3 tempRestriction;
//clean args:
args = iTween.CleanArgs(args);
//set look:
tempRotation=target.transform.eulerAngles;
if (args["looktarget"].GetType() == typeof(Transform)) {
//target.transform.LookAt((Transform)args["looktarget"]);
target.transform.LookAt((Transform)args["looktarget"], (Vector3?)args["up"] ?? Defaults.up);
}else if(args["looktarget"].GetType() == typeof(Vector3)){
//target.transform.LookAt((Vector3)args["looktarget"]);
target.transform.LookAt((Vector3)args["looktarget"], (Vector3?)args["up"] ?? Defaults.up);
}
//axis restriction:
if(args.Contains("axis")){
tempRestriction=target.transform.eulerAngles;
switch((string)args["axis"]){
case "x":
tempRestriction.y=tempRotation.y;
tempRestriction.z=tempRotation.z;
break;
case "y":
tempRestriction.x=tempRotation.x;
tempRestriction.z=tempRotation.z;
break;
case "z":
tempRestriction.x=tempRotation.x;
tempRestriction.y=tempRotation.y;
break;
}
target.transform.eulerAngles=tempRestriction;
}
//set new rotation:
args["rotation"] = tempRotation;
//establish iTween
args["type"]="rotate";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Rotates a GameObject to look at the supplied Vector3 over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> to be the Vector3 that the target will look towards.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void LookTo(GameObject target, Vector3 looktarget, float time){
LookTo(target,Hash("looktarget",looktarget,"time",time));
}
/// <summary>
/// Rotates a GameObject to look at a supplied Transform or Vector3 over time with FULL customization options.
/// </summary>
/// <param name="looktarget">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for a target the GameObject will look at.
/// </param>
/// <param name="axis">
/// A <see cref="System.String"/>. Restricts rotation to the supplied axis only.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void LookTo(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//additional property to ensure ConflictCheck can work correctly since Transforms are refrences:
if(args.Contains("looktarget")){
if (args["looktarget"].GetType() == typeof(Transform)) {
Transform transform = (Transform)args["looktarget"];
args["position"]=new Vector3(transform.position.x,transform.position.y,transform.position.z);
args["rotation"]=new Vector3(transform.eulerAngles.x,transform.eulerAngles.y,transform.eulerAngles.z);
}
}
//establish iTween
args["type"]="look";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Changes a GameObject's position over time to a supplied destination with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="position">
/// A <see cref="Vector3"/> for the destination Vector3.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void MoveTo(GameObject target, Vector3 position, float time){
MoveTo(target,Hash("position",position,"time",time));
}
/// <summary>
/// Changes a GameObject's position over time to a supplied destination with FULL customization options.
/// </summary>
/// <param name="position">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for a point in space the GameObject will animate to.
/// </param>
/// <param name="path">
/// A <see cref="Transform[]"/> or <see cref="Vector3[]"/> for a list of points to draw a Catmull-Rom through for a curved animation path.
/// </param>
/// <param name="movetopath">
/// A <see cref="System.Boolean"/> for whether to automatically generate a curve from the GameObject's current position to the beginning of the path. True by default.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="orienttopath">
/// A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.
/// </param>
/// <param name="looktime">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".
/// </param>
/// <param name="lookahead">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for how much of a percentage to look ahead on a path to influence how strict "orientopath" is.
/// </param>
/// <param name="axis">
/// A <see cref="System.String"/>. Restricts rotation to the supplied axis only.
/// </param>
/// <param name="islocal">
/// A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void MoveTo(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//additional property to ensure ConflictCheck can work correctly since Transforms are refrences:
if(args.Contains("position")){
if (args["position"].GetType() == typeof(Transform)) {
Transform transform = (Transform)args["position"];
args["position"]=new Vector3(transform.position.x,transform.position.y,transform.position.z);
args["rotation"]=new Vector3(transform.eulerAngles.x,transform.eulerAngles.y,transform.eulerAngles.z);
args["scale"]=new Vector3(transform.localScale.x,transform.localScale.y,transform.localScale.z);
}
}
//establish iTween:
args["type"]="move";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Instantly changes a GameObject's position to a supplied destination then returns it to it's starting position over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="position">
/// A <see cref="Vector3"/> for the destination Vector3.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void MoveFrom(GameObject target, Vector3 position, float time){
MoveFrom(target,Hash("position",position,"time",time));
}
/// <summary>
/// Instantly changes a GameObject's position to a supplied destination then returns it to it's starting position over time with FULL customization options.
/// </summary>
/// <param name="position">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for a point in space the GameObject will animate to.
/// </param>
/// <param name="path">
/// A <see cref="Transform[]"/> or <see cref="Vector3[]"/> for a list of points to draw a Catmull-Rom through for a curved animation path.
/// </param>
/// <param name="movetopath">
/// A <see cref="System.Boolean"/> for whether to automatically generate a curve from the GameObject's current position to the beginning of the path. True by default.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="orienttopath">
/// A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.
/// </param>
/// <param name="looktime">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".
/// </param>
/// <param name="lookahead">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for how much of a percentage to look ahead on a path to influence how strict "orientopath" is.
/// </param>
/// <param name="islocal">
/// A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void MoveFrom(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
bool tempIsLocal;
//set tempIsLocal:
if(args.Contains("islocal")){
tempIsLocal = (bool)args["islocal"];
}else{
tempIsLocal = Defaults.isLocal;
}
if(args.Contains("path")){
Vector3[] fromPath;
Vector3[] suppliedPath;
if(args["path"].GetType() == typeof(Vector3[])){
Vector3[] temp = (Vector3[])args["path"];
suppliedPath=new Vector3[temp.Length];
Array.Copy(temp,suppliedPath, temp.Length);
}else{
Transform[] temp = (Transform[])args["path"];
suppliedPath = new Vector3[temp.Length];
for (int i = 0; i < temp.Length; i++) {
suppliedPath[i]=temp[i].position;
}
}
if(suppliedPath[suppliedPath.Length-1] != target.transform.position){
fromPath= new Vector3[suppliedPath.Length+1];
Array.Copy(suppliedPath,fromPath,suppliedPath.Length);
if(tempIsLocal){
fromPath[fromPath.Length-1] = target.transform.localPosition;
target.transform.localPosition=fromPath[0];
}else{
fromPath[fromPath.Length-1] = target.transform.position;
target.transform.position=fromPath[0];
}
args["path"]=fromPath;
}else{
if(tempIsLocal){
target.transform.localPosition=suppliedPath[0];
}else{
target.transform.position=suppliedPath[0];
}
args["path"]=suppliedPath;
}
}else{
Vector3 tempPosition;
Vector3 fromPosition;
//set tempPosition and base fromPosition:
if(tempIsLocal){
tempPosition=fromPosition=target.transform.localPosition;
}else{
tempPosition=fromPosition=target.transform.position;
}
//set augmented fromPosition:
if(args.Contains("position")){
if (args["position"].GetType() == typeof(Transform)){
Transform trans = (Transform)args["position"];
fromPosition=trans.position;
}else if(args["position"].GetType() == typeof(Vector3)){
fromPosition=(Vector3)args["position"];
}
}else{
if (args.Contains("x")) {
fromPosition.x=(float)args["x"];
}
if (args.Contains("y")) {
fromPosition.y=(float)args["y"];
}
if (args.Contains("z")) {
fromPosition.z=(float)args["z"];
}
}
//apply fromPosition:
if(tempIsLocal){
target.transform.localPosition = fromPosition;
}else{
target.transform.position = fromPosition;
}
//set new position arg:
args["position"]=tempPosition;
}
//establish iTween:
args["type"]="move";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Translates a GameObject's position over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount of change in position to move the GameObject.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void MoveAdd(GameObject target, Vector3 amount, float time){
MoveAdd(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Translates a GameObject's position over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount of change in position to move the GameObject.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="orienttopath">
/// A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.
/// </param>
/// <param name="looktime">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".
/// </param>
/// <param name="axis">
/// A <see cref="System.String"/>. Restricts rotation to the supplied axis only.
/// </param>
/// <param name="space">
/// A <see cref="Space"/> or <see cref="System.String"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void MoveAdd(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween:
args["type"]="move";
args["method"]="add";
Launch(target,args);
}
/// <summary>
/// Adds the supplied coordinates to a GameObject's postion with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount of change in position to move the GameObject.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void MoveBy(GameObject target, Vector3 amount, float time){
MoveBy(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Adds the supplied coordinates to a GameObject's position with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount of change in position to move the GameObject.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="orienttopath">
/// A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.
/// </param>
/// <param name="looktime">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".
/// </param>
/// <param name="axis">
/// A <see cref="System.String"/>. Restricts rotation to the supplied axis only.
/// </param>
/// <param name="space">
/// A <see cref="Space"/> or <see cref="System.String"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void MoveBy(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween:
args["type"]="move";
args["method"]="by";
Launch(target,args);
}
/// <summary>
/// Changes a GameObject's scale over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="scale">
/// A <see cref="Vector3"/> for the final scale.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ScaleTo(GameObject target, Vector3 scale, float time){
ScaleTo(target,Hash("scale",scale,"time",time));
}
/// <summary>
/// Changes a GameObject's scale over time with FULL customization options.
/// </summary>
/// <param name="scale">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for the final scale.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ScaleTo(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//additional property to ensure ConflictCheck can work correctly since Transforms are refrences:
if(args.Contains("scale")){
if (args["scale"].GetType() == typeof(Transform)) {
Transform transform = (Transform)args["scale"];
args["position"]=new Vector3(transform.position.x,transform.position.y,transform.position.z);
args["rotation"]=new Vector3(transform.eulerAngles.x,transform.eulerAngles.y,transform.eulerAngles.z);
args["scale"]=new Vector3(transform.localScale.x,transform.localScale.y,transform.localScale.z);
}
}
//establish iTween:
args["type"]="scale";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Instantly changes a GameObject's scale then returns it to it's starting scale over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="scale">
/// A <see cref="Vector3"/> for the final scale.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ScaleFrom(GameObject target, Vector3 scale, float time){
ScaleFrom(target,Hash("scale",scale,"time",time));
}
/// <summary>
/// Instantly changes a GameObject's scale then returns it to it's starting scale over time with FULL customization options.
/// </summary>
/// <param name="scale">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for the final scale.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ScaleFrom(GameObject target, Hashtable args){
Vector3 tempScale;
Vector3 fromScale;
//clean args:
args = iTween.CleanArgs(args);
//set base fromScale:
tempScale=fromScale=target.transform.localScale;
//set augmented fromScale:
if(args.Contains("scale")){
if (args["scale"].GetType() == typeof(Transform)){
Transform trans = (Transform)args["scale"];
fromScale=trans.localScale;
}else if(args["scale"].GetType() == typeof(Vector3)){
fromScale=(Vector3)args["scale"];
}
}else{
if (args.Contains("x")) {
fromScale.x=(float)args["x"];
}
if (args.Contains("y")) {
fromScale.y=(float)args["y"];
}
if (args.Contains("z")) {
fromScale.z=(float)args["z"];
}
}
//apply fromScale:
target.transform.localScale = fromScale;
//set new scale arg:
args["scale"]=tempScale;
//establish iTween:
args["type"]="scale";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Adds to a GameObject's scale over time with FULL customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount of scale to be added to the GameObject's current scale.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ScaleAdd(GameObject target, Vector3 amount, float time){
ScaleAdd(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Adds to a GameObject's scale over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount to be added to the GameObject's current scale.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ScaleAdd(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween:
args["type"]="scale";
args["method"]="add";
Launch(target,args);
}
/// <summary>
/// Multiplies a GameObject's scale over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount of scale to be multiplied by the GameObject's current scale.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ScaleBy(GameObject target, Vector3 amount, float time){
ScaleBy(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Multiplies a GameObject's scale over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount to be multiplied to the GameObject's current scale.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ScaleBy(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween:
args["type"]="scale";
args["method"]="by";
Launch(target,args);
}
/// <summary>
/// Rotates a GameObject to the supplied Euler angles in degrees over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="rotation">
/// A <see cref="Vector3"/> for the target Euler angles in degrees to rotate to.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void RotateTo(GameObject target, Vector3 rotation, float time){
RotateTo(target,Hash("rotation",rotation,"time",time));
}
/// <summary>
/// Rotates a GameObject to the supplied Euler angles in degrees over time with FULL customization options.
/// </summary>
/// <param name="rotation">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for the target Euler angles in degrees to rotate to.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="islocal">
/// A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void RotateTo(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//additional property to ensure ConflictCheck can work correctly since Transforms are refrences:
if(args.Contains("rotation")){
if (args["rotation"].GetType() == typeof(Transform)) {
Transform transform = (Transform)args["rotation"];
args["position"]=new Vector3(transform.position.x,transform.position.y,transform.position.z);
args["rotation"]=new Vector3(transform.eulerAngles.x,transform.eulerAngles.y,transform.eulerAngles.z);
args["scale"]=new Vector3(transform.localScale.x,transform.localScale.y,transform.localScale.z);
}
}
//establish iTween
args["type"]="rotate";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Instantly changes a GameObject's Euler angles in degrees then returns it to it's starting rotation over time (if allowed) with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="rotation">
/// A <see cref="Vector3"/> for the target Euler angles in degrees to rotate from.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void RotateFrom(GameObject target, Vector3 rotation, float time){
RotateFrom(target,Hash("rotation",rotation,"time",time));
}
/// <summary>
/// Instantly changes a GameObject's Euler angles in degrees then returns it to it's starting rotation over time (if allowed) with FULL customization options.
/// </summary>
/// <param name="rotation">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for the target Euler angles in degrees to rotate to.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="islocal">
/// A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void RotateFrom(GameObject target, Hashtable args){
Vector3 tempRotation;
Vector3 fromRotation;
bool tempIsLocal;
//clean args:
args = iTween.CleanArgs(args);
//set tempIsLocal:
if(args.Contains("islocal")){
tempIsLocal = (bool)args["islocal"];
}else{
tempIsLocal = Defaults.isLocal;
}
//set tempRotation and base fromRotation:
if(tempIsLocal){
tempRotation=fromRotation=target.transform.localEulerAngles;
}else{
tempRotation=fromRotation=target.transform.eulerAngles;
}
//set augmented fromRotation:
if(args.Contains("rotation")){
if (args["rotation"].GetType() == typeof(Transform)){
Transform trans = (Transform)args["rotation"];
fromRotation=trans.eulerAngles;
}else if(args["rotation"].GetType() == typeof(Vector3)){
fromRotation=(Vector3)args["rotation"];
}
}else{
if (args.Contains("x")) {
fromRotation.x=(float)args["x"];
}
if (args.Contains("y")) {
fromRotation.y=(float)args["y"];
}
if (args.Contains("z")) {
fromRotation.z=(float)args["z"];
}
}
//apply fromRotation:
if(tempIsLocal){
target.transform.localEulerAngles = fromRotation;
}else{
target.transform.eulerAngles = fromRotation;
}
//set new rotation arg:
args["rotation"]=tempRotation;
//establish iTween:
args["type"]="rotate";
args["method"]="to";
Launch(target,args);
}
/// <summary>
/// Adds supplied Euler angles in degrees to a GameObject's rotation over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount of Euler angles in degrees to add to the current rotation of the GameObject.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void RotateAdd(GameObject target, Vector3 amount, float time){
RotateAdd(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Adds supplied Euler angles in degrees to a GameObject's rotation over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount of Euler angles in degrees to add to the current rotation of the GameObject.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="space">
/// A <see cref="Space"/> or <see cref="System.String"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void RotateAdd(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween:
args["type"]="rotate";
args["method"]="add";
Launch(target,args);
}
/// <summary>
/// Multiplies supplied values by 360 and rotates a GameObject by calculated amount over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount to be multiplied by 360 to rotate the GameObject.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void RotateBy(GameObject target, Vector3 amount, float time){
RotateBy(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Multiplies supplied values by 360 and rotates a GameObject by calculated amount over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the amount to be multiplied by 360 to rotate the GameObject.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="space">
/// A <see cref="Space"/> or <see cref="System.String"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.
/// </param>
/// <param name="islocal">
/// A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="speed">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="easetype">
/// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void RotateBy(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween
args["type"]="rotate";
args["method"]="by";
Launch(target,args);
}
/// <summary>
/// Randomly shakes a GameObject's position by a diminishing amount over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ShakePosition(GameObject target, Vector3 amount, float time){
ShakePosition(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Randomly shakes a GameObject's position by a diminishing amount over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.
/// </param>
/// <param name="islocal">
/// A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.
/// </param>
/// <param name="orienttopath">
/// A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.
/// </param>
/// <param name="looktime">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with shakes)
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ShakePosition(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween
args["type"]="shake";
args["method"]="position";
Launch(target,args);
}
/// <summary>
/// Randomly shakes a GameObject's scale by a diminishing amount over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ShakeScale(GameObject target, Vector3 amount, float time){
ShakeScale(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Randomly shakes a GameObject's scale by a diminishing amount over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with shakes)
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ShakeScale(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween
args["type"]="shake";
args["method"]="scale";
Launch(target,args);
}
/// <summary>
/// Randomly shakes a GameObject's rotation by a diminishing amount over time with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ShakeRotation(GameObject target, Vector3 amount, float time){
ShakeRotation(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Randomly shakes a GameObject's rotation by a diminishing amount over time with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.
/// </param>
/// <param name="space">
/// A <see cref="Space"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with shakes)
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void ShakeRotation(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween
args["type"]="shake";
args["method"]="rotation";
Launch(target,args);
}
/// <summary>
/// Applies a jolt of force to a GameObject's position and wobbles it back to its initial position with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of the punch.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void PunchPosition(GameObject target, Vector3 amount, float time){
PunchPosition(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Applies a jolt of force to a GameObject's position and wobbles it back to its initial position with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.
/// </param>
/// <param name="space">
/// A <see cref="Space"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.
/// </param>
/// <param name="looktime">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget".
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with punches)
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void PunchPosition(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween
args["type"]="punch";
args["method"]="position";
args["easetype"]=EaseType.punch;
Launch(target,args);
}
/// <summary>
/// Applies a jolt of force to a GameObject's rotation and wobbles it back to its initial rotation with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of the punch.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void PunchRotation(GameObject target, Vector3 amount, float time){
PunchRotation(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Applies a jolt of force to a GameObject's rotation and wobbles it back to its initial rotation with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.
/// </param>
/// <param name="space">
/// A <see cref="Space"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with punches)
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void PunchRotation(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween
args["type"]="punch";
args["method"]="rotation";
args["easetype"]=EaseType.punch;
Launch(target,args);
}
/// <summary>
/// Applies a jolt of force to a GameObject's scale and wobbles it back to its initial scale with MINIMUM customization options.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of the punch.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void PunchScale(GameObject target, Vector3 amount, float time){
PunchScale(target,Hash("amount",amount,"time",time));
}
/// <summary>
/// Applies a jolt of force to a GameObject's scale and wobbles it back to its initial scale with FULL customization options.
/// </summary>
/// <param name="amount">
/// A <see cref="Vector3"/> for the magnitude of shake.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="delay">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
/// </param>
/// <param name="looptype">
/// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with punches)
/// </param>
/// <param name="onstart">
/// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
/// </param>
/// <param name="onstarttarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
/// </param>
/// <param name="onstartparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
/// </param>
/// <param name="onupdate">
/// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
/// </param>
/// <param name="onupdatetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
/// </param>
/// <param name="onupdateparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
/// </param>
/// <param name="oncomplete">
/// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
/// </param>
/// <param name="oncompletetarget">
/// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
/// </param>
/// <param name="oncompleteparams">
/// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
/// </param>
public static void PunchScale(GameObject target, Hashtable args){
//clean args:
args = iTween.CleanArgs(args);
//establish iTween
args["type"]="punch";
args["method"]="scale";
args["easetype"]=EaseType.punch;
Launch(target,args);
}
#endregion
#region #2 Generate Method Targets
//call correct set target method and set tween application delegate:
void GenerateTargets(){
switch (type) {
case "value":
switch (method) {
case "float":
GenerateFloatTargets();
apply = new ApplyTween(ApplyFloatTargets);
break;
case "vector2":
GenerateVector2Targets();
apply = new ApplyTween(ApplyVector2Targets);
break;
case "vector3":
GenerateVector3Targets();
apply = new ApplyTween(ApplyVector3Targets);
break;
case "color":
GenerateColorTargets();
apply = new ApplyTween(ApplyColorTargets);
break;
case "rect":
GenerateRectTargets();
apply = new ApplyTween(ApplyRectTargets);
break;
}
break;
case "color":
switch (method) {
case "to":
GenerateColorToTargets();
apply = new ApplyTween(ApplyColorToTargets);
break;
}
break;
case "audio":
switch (method) {
case "to":
GenerateAudioToTargets();
apply = new ApplyTween(ApplyAudioToTargets);
break;
}
break;
case "move":
switch (method) {
case "to":
//using a path?
if(tweenArguments.Contains("path")){
GenerateMoveToPathTargets();
apply = new ApplyTween(ApplyMoveToPathTargets);
}else{ //not using a path?
GenerateMoveToTargets();
apply = new ApplyTween(ApplyMoveToTargets);
}
break;
case "by":
case "add":
GenerateMoveByTargets();
apply = new ApplyTween(ApplyMoveByTargets);
break;
}
break;
case "scale":
switch (method){
case "to":
GenerateScaleToTargets();
apply = new ApplyTween(ApplyScaleToTargets);
break;
case "by":
GenerateScaleByTargets();
apply = new ApplyTween(ApplyScaleToTargets);
break;
case "add":
GenerateScaleAddTargets();
apply = new ApplyTween(ApplyScaleToTargets);
break;
}
break;
case "rotate":
switch (method) {
case "to":
GenerateRotateToTargets();
apply = new ApplyTween(ApplyRotateToTargets);
break;
case "add":
GenerateRotateAddTargets();
apply = new ApplyTween(ApplyRotateAddTargets);
break;
case "by":
GenerateRotateByTargets();
apply = new ApplyTween(ApplyRotateAddTargets);
break;
}
break;
case "shake":
switch (method) {
case "position":
GenerateShakePositionTargets();
apply = new ApplyTween(ApplyShakePositionTargets);
break;
case "scale":
GenerateShakeScaleTargets();
apply = new ApplyTween(ApplyShakeScaleTargets);
break;
case "rotation":
GenerateShakeRotationTargets();
apply = new ApplyTween(ApplyShakeRotationTargets);
break;
}
break;
case "punch":
switch (method) {
case "position":
GeneratePunchPositionTargets();
apply = new ApplyTween(ApplyPunchPositionTargets);
break;
case "rotation":
GeneratePunchRotationTargets();
apply = new ApplyTween(ApplyPunchRotationTargets);
break;
case "scale":
GeneratePunchScaleTargets();
apply = new ApplyTween(ApplyPunchScaleTargets);
break;
}
break;
case "look":
switch (method) {
case "to":
GenerateLookToTargets();
apply = new ApplyTween(ApplyLookToTargets);
break;
}
break;
case "stab":
GenerateStabTargets();
apply = new ApplyTween(ApplyStabTargets);
break;
}
}
#endregion
#region #3 Generate Specific Targets
void GenerateRectTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
rects=new Rect[3];
//from and to values:
rects[0]=(Rect)tweenArguments["from"];
rects[1]=(Rect)tweenArguments["to"];
}
void GenerateColorTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
colors=new Color[1,3];
//from and to values:
colors[0,0]=(Color)tweenArguments["from"];
colors[0,1]=(Color)tweenArguments["to"];
}
void GenerateVector3Targets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector3s=new Vector3[3];
//from and to values:
vector3s[0]=(Vector3)tweenArguments["from"];
vector3s[1]=(Vector3)tweenArguments["to"];
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateVector2Targets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector2s=new Vector2[3];
//from and to values:
vector2s[0]=(Vector2)tweenArguments["from"];
vector2s[1]=(Vector2)tweenArguments["to"];
//need for speed?
if(tweenArguments.Contains("speed")){
Vector3 fromV3 = new Vector3(vector2s[0].x,vector2s[0].y,0);
Vector3 toV3 = new Vector3(vector2s[1].x,vector2s[1].y,0);
float distance = Math.Abs(Vector3.Distance(fromV3,toV3));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateFloatTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
floats=new float[3];
//from and to values:
floats[0]=(float)tweenArguments["from"];
floats[1]=(float)tweenArguments["to"];
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(floats[0] - floats[1]);
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateColorToTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
//colors = new Color[3];
//from and init to values:
if(GetComponent(typeof(GUITexture))){
colors = new Color[1,3];
colors[0,0] = colors[0,1] = guiTexture.color;
}else if(GetComponent(typeof(GUIText))){
colors = new Color[1,3];
colors[0,0] = colors[0,1] = guiText.material.color;
}else if(renderer){
colors = new Color[renderer.materials.Length,3];
for (int i = 0; i < renderer.materials.Length; i++) {
colors[i,0]=renderer.materials[i].GetColor(namedcolorvalue.ToString());
colors[i,1]=renderer.materials[i].GetColor(namedcolorvalue.ToString());
}
//colors[0] = colors[1] = renderer.material.color;
}else if(light){
colors = new Color[1,3];
colors[0,0] = colors[0,1] = light.color;
}else{
colors = new Color[1,3]; //empty placeholder incase the GO is perhaps an empty holder or something similar
}
//to values:
if (tweenArguments.Contains("color")) {
//colors[1]=(Color)tweenArguments["color"];
for (int i = 0; i < colors.GetLength(0); i++) {
colors[i,1]=(Color)tweenArguments["color"];
}
}else{
if (tweenArguments.Contains("r")) {
//colors[1].r=(float)tweenArguments["r"];
for (int i = 0; i < colors.GetLength(0); i++) {
colors[i,1].r=(float)tweenArguments["r"];
}
}
if (tweenArguments.Contains("g")) {
//colors[1].g=(float)tweenArguments["g"];
for (int i = 0; i < colors.GetLength(0); i++) {
colors[i,1].g=(float)tweenArguments["g"];
}
}
if (tweenArguments.Contains("b")) {
//colors[1].b=(float)tweenArguments["b"];
for (int i = 0; i < colors.GetLength(0); i++) {
colors[i,1].b=(float)tweenArguments["b"];
}
}
if (tweenArguments.Contains("a")) {
//colors[1].a=(float)tweenArguments["a"];
for (int i = 0; i < colors.GetLength(0); i++) {
colors[i,1].a=(float)tweenArguments["a"];
}
}
}
//alpha or amount?
if(tweenArguments.Contains("amount")){
//colors[1].a=(float)tweenArguments["amount"];
for (int i = 0; i < colors.GetLength(0); i++) {
colors[i,1].a=(float)tweenArguments["amount"];
}
}else if(tweenArguments.Contains("alpha")){
//colors[1].a=(float)tweenArguments["alpha"];
for (int i = 0; i < colors.GetLength(0); i++) {
colors[i,1].a=(float)tweenArguments["alpha"];
}
}
}
void GenerateAudioToTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector2s=new Vector2[3];
//set audioSource:
if(tweenArguments.Contains("audiosource")){
audioSource=(AudioSource)tweenArguments["audiosource"];
}else{
if(GetComponent(typeof(AudioSource))){
audioSource=audio;
}else{
//throw error if no AudioSource is available:
Debug.LogError("iTween Error: AudioTo requires an AudioSource.");
Dispose();
}
}
//from values and default to values:
vector2s[0]=vector2s[1]=new Vector2(audioSource.volume,audioSource.pitch);
//to values:
if (tweenArguments.Contains("volume")) {
vector2s[1].x=(float)tweenArguments["volume"];
}
if (tweenArguments.Contains("pitch")) {
vector2s[1].y=(float)tweenArguments["pitch"];
}
}
void GenerateStabTargets(){
//set audioSource:
if(tweenArguments.Contains("audiosource")){
audioSource=(AudioSource)tweenArguments["audiosource"];
}else{
if(GetComponent(typeof(AudioSource))){
audioSource=audio;
}else{
//add and populate AudioSource if one doesn't exist:
gameObject.AddComponent(typeof(AudioSource));
audioSource=audio;
audioSource.playOnAwake=false;
}
}
//populate audioSource's clip:
audioSource.clip=(AudioClip)tweenArguments["audioclip"];
//set audio's pitch and volume if requested:
if(tweenArguments.Contains("pitch")){
audioSource.pitch=(float)tweenArguments["pitch"];
}
if(tweenArguments.Contains("volume")){
audioSource.volume=(float)tweenArguments["volume"];
}
//set run time based on length of clip after pitch is augmented
time=audioSource.clip.length/audioSource.pitch;
}
void GenerateLookToTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector3s=new Vector3[3];
//from values:
vector3s[0]=transform.eulerAngles;
//set look:
if(tweenArguments.Contains("looktarget")){
if (tweenArguments["looktarget"].GetType() == typeof(Transform)) {
//transform.LookAt((Transform)tweenArguments["looktarget"]);
transform.LookAt((Transform)tweenArguments["looktarget"], (Vector3?)tweenArguments["up"] ?? Defaults.up);
}else if(tweenArguments["looktarget"].GetType() == typeof(Vector3)){
//transform.LookAt((Vector3)tweenArguments["looktarget"]);
transform.LookAt((Vector3)tweenArguments["looktarget"], (Vector3?)tweenArguments["up"] ?? Defaults.up);
}
}else{
Debug.LogError("iTween Error: LookTo needs a 'looktarget' property!");
Dispose();
}
//to values:
vector3s[1]=transform.eulerAngles;
transform.eulerAngles=vector3s[0];
//axis restriction:
if(tweenArguments.Contains("axis")){
switch((string)tweenArguments["axis"]){
case "x":
vector3s[1].y=vector3s[0].y;
vector3s[1].z=vector3s[0].z;
break;
case "y":
vector3s[1].x=vector3s[0].x;
vector3s[1].z=vector3s[0].z;
break;
case "z":
vector3s[1].x=vector3s[0].x;
vector3s[1].y=vector3s[0].y;
break;
}
}
//shortest distance:
vector3s[1]=new Vector3(clerp(vector3s[0].x,vector3s[1].x,1),clerp(vector3s[0].y,vector3s[1].y,1),clerp(vector3s[0].z,vector3s[1].z,1));
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateMoveToPathTargets(){
Vector3[] suppliedPath;
//create and store path points:
if(tweenArguments["path"].GetType() == typeof(Vector3[])){
Vector3[] temp = (Vector3[])tweenArguments["path"];
//if only one point is supplied fall back to MoveTo's traditional use since we can't have a curve with one value:
if(temp.Length==1){
Debug.LogError("iTween Error: Attempting a path movement with MoveTo requires an array of more than 1 entry!");
Dispose();
}
suppliedPath=new Vector3[temp.Length];
Array.Copy(temp,suppliedPath, temp.Length);
}else{
Transform[] temp = (Transform[])tweenArguments["path"];
//if only one point is supplied fall back to MoveTo's traditional use since we can't have a curve with one value:
if(temp.Length==1){
Debug.LogError("iTween Error: Attempting a path movement with MoveTo requires an array of more than 1 entry!");
Dispose();
}
suppliedPath = new Vector3[temp.Length];
for (int i = 0; i < temp.Length; i++) {
suppliedPath[i]=temp[i].position;
}
}
//do we need to plot a path to get to the beginning of the supplied path?
bool plotStart;
int offset;
if(transform.position != suppliedPath[0]){
if(!tweenArguments.Contains("movetopath") || (bool)tweenArguments["movetopath"]==true){
plotStart=true;
offset=3;
}else{
plotStart=false;
offset=2;
}
}else{
plotStart=false;
offset=2;
}
//build calculated path:
vector3s = new Vector3[suppliedPath.Length+offset];
if(plotStart){
vector3s[1]=transform.position;
offset=2;
}else{
offset=1;
}
//populate calculate path;
Array.Copy(suppliedPath,0,vector3s,offset,suppliedPath.Length);
//populate start and end control points:
//vector3s[0] = vector3s[1] - vector3s[2];
vector3s[0] = vector3s[1] + (vector3s[1] - vector3s[2]);
vector3s[vector3s.Length-1] = vector3s[vector3s.Length-2] + (vector3s[vector3s.Length-2] - vector3s[vector3s.Length-3]);
//is this a closed, continuous loop? yes? well then so let's make a continuous Catmull-Rom spline!
if(vector3s[1] == vector3s[vector3s.Length-2]){
Vector3[] tmpLoopSpline = new Vector3[vector3s.Length];
Array.Copy(vector3s,tmpLoopSpline,vector3s.Length);
tmpLoopSpline[0]=tmpLoopSpline[tmpLoopSpline.Length-3];
tmpLoopSpline[tmpLoopSpline.Length-1]=tmpLoopSpline[2];
vector3s=new Vector3[tmpLoopSpline.Length];
Array.Copy(tmpLoopSpline,vector3s,tmpLoopSpline.Length);
}
//create Catmull-Rom path:
path = new CRSpline(vector3s);
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = PathLength(vector3s);
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateMoveToTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector3s=new Vector3[3];
//from values:
if (isLocal) {
vector3s[0]=vector3s[1]=transform.localPosition;
}else{
vector3s[0]=vector3s[1]=transform.position;
}
//to values:
if (tweenArguments.Contains("position")) {
if (tweenArguments["position"].GetType() == typeof(Transform)){
Transform trans = (Transform)tweenArguments["position"];
vector3s[1]=trans.position;
}else if(tweenArguments["position"].GetType() == typeof(Vector3)){
vector3s[1]=(Vector3)tweenArguments["position"];
}
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
//handle orient to path request:
if(tweenArguments.Contains("orienttopath") && (bool)tweenArguments["orienttopath"]){
tweenArguments["looktarget"] = vector3s[1];
}
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateMoveByTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation, [3] previous value for Translate usage to allow Space utilization, [4] original rotation to make sure look requests don't interfere with the direction object should move in, [5] for dial in location:
vector3s=new Vector3[6];
//grab starting rotation:
vector3s[4] = transform.eulerAngles;
//from values:
vector3s[0]=vector3s[1]=vector3s[3]=transform.position;
//to values:
if (tweenArguments.Contains("amount")) {
vector3s[1]=vector3s[0] + (Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=vector3s[0].x + (float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=vector3s[0].y +(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=vector3s[0].z + (float)tweenArguments["z"];
}
}
//calculation for dial in:
transform.Translate(vector3s[1],space);
vector3s[5] = transform.position;
transform.position=vector3s[0];
//handle orient to path request:
if(tweenArguments.Contains("orienttopath") && (bool)tweenArguments["orienttopath"]){
tweenArguments["looktarget"] = vector3s[1];
}
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateScaleToTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector3s=new Vector3[3];
//from values:
vector3s[0]=vector3s[1]=transform.localScale;
//to values:
if (tweenArguments.Contains("scale")) {
if (tweenArguments["scale"].GetType() == typeof(Transform)){
Transform trans = (Transform)tweenArguments["scale"];
vector3s[1]=trans.localScale;
}else if(tweenArguments["scale"].GetType() == typeof(Vector3)){
vector3s[1]=(Vector3)tweenArguments["scale"];
}
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateScaleByTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector3s=new Vector3[3];
//from values:
vector3s[0]=vector3s[1]=transform.localScale;
//to values:
if (tweenArguments.Contains("amount")) {
vector3s[1]=Vector3.Scale(vector3s[1],(Vector3)tweenArguments["amount"]);
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x*=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y*=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z*=(float)tweenArguments["z"];
}
}
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateScaleAddTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector3s=new Vector3[3];
//from values:
vector3s[0]=vector3s[1]=transform.localScale;
//to values:
if (tweenArguments.Contains("amount")) {
vector3s[1]+=(Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x+=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y+=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z+=(float)tweenArguments["z"];
}
}
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateRotateToTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector3s=new Vector3[3];
//from values:
if (isLocal) {
vector3s[0]=vector3s[1]=transform.localEulerAngles;
}else{
vector3s[0]=vector3s[1]=transform.eulerAngles;
}
//to values:
if (tweenArguments.Contains("rotation")) {
if (tweenArguments["rotation"].GetType() == typeof(Transform)){
Transform trans = (Transform)tweenArguments["rotation"];
vector3s[1]=trans.eulerAngles;
}else if(tweenArguments["rotation"].GetType() == typeof(Vector3)){
vector3s[1]=(Vector3)tweenArguments["rotation"];
}
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
//shortest distance:
vector3s[1]=new Vector3(clerp(vector3s[0].x,vector3s[1].x,1),clerp(vector3s[0].y,vector3s[1].y,1),clerp(vector3s[0].z,vector3s[1].z,1));
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateRotateAddTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation, [3] previous value for Rotate usage to allow Space utilization:
vector3s=new Vector3[5];
//from values:
vector3s[0]=vector3s[1]=vector3s[3]=transform.eulerAngles;
//to values:
if (tweenArguments.Contains("amount")) {
vector3s[1]+=(Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x+=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y+=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z+=(float)tweenArguments["z"];
}
}
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateRotateByTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation, [3] previous value for Rotate usage to allow Space utilization:
vector3s=new Vector3[4];
//from values:
vector3s[0]=vector3s[1]=vector3s[3]=transform.eulerAngles;
//to values:
if (tweenArguments.Contains("amount")) {
vector3s[1]+=Vector3.Scale((Vector3)tweenArguments["amount"],new Vector3(360,360,360));
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x+=360 * (float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y+=360 * (float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z+=360 * (float)tweenArguments["z"];
}
}
//need for speed?
if(tweenArguments.Contains("speed")){
float distance = Math.Abs(Vector3.Distance(vector3s[0],vector3s[1]));
time = distance/(float)tweenArguments["speed"];
}
}
void GenerateShakePositionTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation, [3] original rotation to make sure look requests don't interfere with the direction object should move in:
vector3s=new Vector3[4];
//grab starting rotation:
vector3s[3] = transform.eulerAngles;
//root:
vector3s[0]=transform.position;
//amount:
if (tweenArguments.Contains("amount")) {
vector3s[1]=(Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
}
void GenerateShakeScaleTargets(){
//values holder [0] root value, [1] amount, [2] generated amount:
vector3s=new Vector3[3];
//root:
vector3s[0]=transform.localScale;
//amount:
if (tweenArguments.Contains("amount")) {
vector3s[1]=(Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
}
void GenerateShakeRotationTargets(){
//values holder [0] root value, [1] amount, [2] generated amount:
vector3s=new Vector3[3];
//root:
vector3s[0]=transform.eulerAngles;
//amount:
if (tweenArguments.Contains("amount")) {
vector3s[1]=(Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
}
void GeneratePunchPositionTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation, [3] previous value for Translate usage to allow Space utilization, [4] original rotation to make sure look requests don't interfere with the direction object should move in:
vector3s=new Vector3[5];
//grab starting rotation:
vector3s[4] = transform.eulerAngles;
//from values:
vector3s[0]=transform.position;
vector3s[1]=vector3s[3]=Vector3.zero;
//to values:
if (tweenArguments.Contains("amount")) {
vector3s[1]=(Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
}
void GeneratePunchRotationTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation, [3] previous value for Translate usage to allow Space utilization:
vector3s=new Vector3[4];
//from values:
vector3s[0]=transform.eulerAngles;
vector3s[1]=vector3s[3]=Vector3.zero;
//to values:
if (tweenArguments.Contains("amount")) {
vector3s[1]=(Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
}
void GeneratePunchScaleTargets(){
//values holder [0] from, [1] to, [2] calculated value from ease equation:
vector3s=new Vector3[3];
//from values:
vector3s[0]=transform.localScale;
vector3s[1]=Vector3.zero;
//to values:
if (tweenArguments.Contains("amount")) {
vector3s[1]=(Vector3)tweenArguments["amount"];
}else{
if (tweenArguments.Contains("x")) {
vector3s[1].x=(float)tweenArguments["x"];
}
if (tweenArguments.Contains("y")) {
vector3s[1].y=(float)tweenArguments["y"];
}
if (tweenArguments.Contains("z")) {
vector3s[1].z=(float)tweenArguments["z"];
}
}
}
#endregion
#region #4 Apply Targets
void ApplyRectTargets(){
//calculate:
rects[2].x = ease(rects[0].x,rects[1].x,percentage);
rects[2].y = ease(rects[0].y,rects[1].y,percentage);
rects[2].width = ease(rects[0].width,rects[1].width,percentage);
rects[2].height = ease(rects[0].height,rects[1].height,percentage);
//apply:
tweenArguments["onupdateparams"]=rects[2];
//dial in:
if(percentage==1){
tweenArguments["onupdateparams"]=rects[1];
}
}
void ApplyColorTargets(){
//calculate:
colors[0,2].r = ease(colors[0,0].r,colors[0,1].r,percentage);
colors[0,2].g = ease(colors[0,0].g,colors[0,1].g,percentage);
colors[0,2].b = ease(colors[0,0].b,colors[0,1].b,percentage);
colors[0,2].a = ease(colors[0,0].a,colors[0,1].a,percentage);
//apply:
tweenArguments["onupdateparams"]=colors[0,2];
//dial in:
if(percentage==1){
tweenArguments["onupdateparams"]=colors[0,1];
}
}
void ApplyVector3Targets(){
//calculate:
vector3s[2].x = ease(vector3s[0].x,vector3s[1].x,percentage);
vector3s[2].y = ease(vector3s[0].y,vector3s[1].y,percentage);
vector3s[2].z = ease(vector3s[0].z,vector3s[1].z,percentage);
//apply:
tweenArguments["onupdateparams"]=vector3s[2];
//dial in:
if(percentage==1){
tweenArguments["onupdateparams"]=vector3s[1];
}
}
void ApplyVector2Targets(){
//calculate:
vector2s[2].x = ease(vector2s[0].x,vector2s[1].x,percentage);
vector2s[2].y = ease(vector2s[0].y,vector2s[1].y,percentage);
//apply:
tweenArguments["onupdateparams"]=vector2s[2];
//dial in:
if(percentage==1){
tweenArguments["onupdateparams"]=vector2s[1];
}
}
void ApplyFloatTargets(){
//calculate:
floats[2] = ease(floats[0],floats[1],percentage);
//apply:
tweenArguments["onupdateparams"]=floats[2];
//dial in:
if(percentage==1){
tweenArguments["onupdateparams"]=floats[1];
}
}
void ApplyColorToTargets(){
//calculate:
for (int i = 0; i < colors.GetLength(0); i++) {
colors[i,2].r = ease(colors[i,0].r,colors[i,1].r,percentage);
colors[i,2].g = ease(colors[i,0].g,colors[i,1].g,percentage);
colors[i,2].b = ease(colors[i,0].b,colors[i,1].b,percentage);
colors[i,2].a = ease(colors[i,0].a,colors[i,1].a,percentage);
}
/*
colors[2].r = ease(colors[0].r,colors[1].r,percentage);
colors[2].g = ease(colors[0].g,colors[1].g,percentage);
colors[2].b = ease(colors[0].b,colors[1].b,percentage);
colors[2].a = ease(colors[0].a,colors[1].a,percentage);
*/
//apply:
if(GetComponent(typeof(GUITexture))){
//guiTexture.color=colors[2];
guiTexture.color=colors[0,2];
}else if(GetComponent(typeof(GUIText))){
//guiText.material.color=colors[2];
guiText.material.color=colors[0,2];
}else if(renderer){
//renderer.material.color=colors[2];
for (int i = 0; i < colors.GetLength(0); i++) {
renderer.materials[i].SetColor(namedcolorvalue.ToString(),colors[i,2]);
}
}else if(light){
//light.color=colors[2];
light.color=colors[0,2];
}
//dial in:
if(percentage==1){
if(GetComponent(typeof(GUITexture))){
//guiTexture.color=colors[1];
guiTexture.color=colors[0,1];
}else if(GetComponent(typeof(GUIText))){
//guiText.material.color=colors[1];
guiText.material.color=colors[0,1];
}else if(renderer){
//renderer.material.color=colors[1];
for (int i = 0; i < colors.GetLength(0); i++) {
renderer.materials[i].SetColor(namedcolorvalue.ToString(),colors[i,1]);
}
}else if(light){
//light.color=colors[1];
light.color=colors[0,1];
}
}
}
void ApplyAudioToTargets(){
//calculate:
vector2s[2].x = ease(vector2s[0].x,vector2s[1].x,percentage);
vector2s[2].y = ease(vector2s[0].y,vector2s[1].y,percentage);
//apply:
audioSource.volume=vector2s[2].x;
audioSource.pitch=vector2s[2].y;
//dial in:
if(percentage==1){
audioSource.volume=vector2s[1].x;
audioSource.pitch=vector2s[1].y;
}
}
void ApplyStabTargets(){
//unnecessary but here just in case
}
void ApplyMoveToPathTargets(){
preUpdate = transform.position;
float t = ease(0,1,percentage);
float lookAheadAmount;
//clamp easing equation results as "back" will fail since overshoots aren't handled in the Catmull-Rom interpolation:
if(isLocal){
transform.localPosition=path.Interp(Mathf.Clamp(t,0,1));
}else{
transform.position=path.Interp(Mathf.Clamp(t,0,1));
}
//handle orient to path request:
if(tweenArguments.Contains("orienttopath") && (bool)tweenArguments["orienttopath"]){
//plot a point slightly ahead in the interpolation by pushing the percentage forward using the default lookahead value:
float tLook;
if(tweenArguments.Contains("lookahead")){
lookAheadAmount = (float)tweenArguments["lookahead"];
}else{
lookAheadAmount = Defaults.lookAhead;
}
//tLook = ease(0,1,percentage+lookAheadAmount);
tLook = ease(0,1, Mathf.Min(1f, percentage+lookAheadAmount));
//locate new leading point with a clamp as stated above:
//Vector3 lookDistance = path.Interp(Mathf.Clamp(tLook,0,1)) - transform.position;
tweenArguments["looktarget"] = path.Interp(Mathf.Clamp(tLook,0,1));
}
//need physics?
postUpdate=transform.position;
if(physics){
transform.position=preUpdate;
rigidbody.MovePosition(postUpdate);
}
}
void ApplyMoveToTargets(){
//record current:
preUpdate=transform.position;
//calculate:
vector3s[2].x = ease(vector3s[0].x,vector3s[1].x,percentage);
vector3s[2].y = ease(vector3s[0].y,vector3s[1].y,percentage);
vector3s[2].z = ease(vector3s[0].z,vector3s[1].z,percentage);
//apply:
if (isLocal) {
transform.localPosition=vector3s[2];
}else{
transform.position=vector3s[2];
}
//dial in:
if(percentage==1){
if (isLocal) {
transform.localPosition=vector3s[1];
}else{
transform.position=vector3s[1];
}
}
//need physics?
postUpdate=transform.position;
if(physics){
transform.position=preUpdate;
rigidbody.MovePosition(postUpdate);
}
}
void ApplyMoveByTargets(){
preUpdate = transform.position;
//reset rotation to prevent look interferences as object rotates and attempts to move with translate and record current rotation
Vector3 currentRotation = new Vector3();
if(tweenArguments.Contains("looktarget")){
currentRotation = transform.eulerAngles;
transform.eulerAngles = vector3s[4];
}
//calculate:
vector3s[2].x = ease(vector3s[0].x,vector3s[1].x,percentage);
vector3s[2].y = ease(vector3s[0].y,vector3s[1].y,percentage);
vector3s[2].z = ease(vector3s[0].z,vector3s[1].z,percentage);
//apply:
transform.Translate(vector3s[2]-vector3s[3],space);
//record:
vector3s[3]=vector3s[2];
//reset rotation:
if(tweenArguments.Contains("looktarget")){
transform.eulerAngles = currentRotation;
}
/*
//dial in:
if(percentage==1){
transform.position=vector3s[5];
}
*/
//need physics?
postUpdate=transform.position;
if(physics){
transform.position=preUpdate;
rigidbody.MovePosition(postUpdate);
}
}
void ApplyScaleToTargets(){
//calculate:
vector3s[2].x = ease(vector3s[0].x,vector3s[1].x,percentage);
vector3s[2].y = ease(vector3s[0].y,vector3s[1].y,percentage);
vector3s[2].z = ease(vector3s[0].z,vector3s[1].z,percentage);
//apply:
transform.localScale=vector3s[2];
//dial in:
if(percentage==1){
transform.localScale=vector3s[1];
}
}
void ApplyLookToTargets(){
//calculate:
vector3s[2].x = ease(vector3s[0].x,vector3s[1].x,percentage);
vector3s[2].y = ease(vector3s[0].y,vector3s[1].y,percentage);
vector3s[2].z = ease(vector3s[0].z,vector3s[1].z,percentage);
//apply:
if (isLocal) {
transform.localRotation = Quaternion.Euler(vector3s[2]);
}else{
transform.rotation = Quaternion.Euler(vector3s[2]);
};
}
void ApplyRotateToTargets(){
preUpdate=transform.eulerAngles;
//calculate:
vector3s[2].x = ease(vector3s[0].x,vector3s[1].x,percentage);
vector3s[2].y = ease(vector3s[0].y,vector3s[1].y,percentage);
vector3s[2].z = ease(vector3s[0].z,vector3s[1].z,percentage);
//apply:
if (isLocal) {
transform.localRotation = Quaternion.Euler(vector3s[2]);
}else{
transform.rotation = Quaternion.Euler(vector3s[2]);
};
//dial in:
if(percentage==1){
if (isLocal) {
transform.localRotation = Quaternion.Euler(vector3s[1]);
}else{
transform.rotation = Quaternion.Euler(vector3s[1]);
};
}
//need physics?
postUpdate=transform.eulerAngles;
if(physics){
transform.eulerAngles=preUpdate;
rigidbody.MoveRotation(Quaternion.Euler(postUpdate));
}
}
void ApplyRotateAddTargets(){
preUpdate = transform.eulerAngles;
//calculate:
vector3s[2].x = ease(vector3s[0].x,vector3s[1].x,percentage);
vector3s[2].y = ease(vector3s[0].y,vector3s[1].y,percentage);
vector3s[2].z = ease(vector3s[0].z,vector3s[1].z,percentage);
//apply:
transform.Rotate(vector3s[2]-vector3s[3],space);
//record:
vector3s[3]=vector3s[2];
//need physics?
postUpdate=transform.eulerAngles;
if(physics){
transform.eulerAngles=preUpdate;
rigidbody.MoveRotation(Quaternion.Euler(postUpdate));
}
}
void ApplyShakePositionTargets(){
//preUpdate = transform.position;
if (isLocal) {
preUpdate = transform.localPosition;
}else{
preUpdate = transform.position;
}
//reset rotation to prevent look interferences as object rotates and attempts to move with translate and record current rotation
Vector3 currentRotation = new Vector3();
if(tweenArguments.Contains("looktarget")){
currentRotation = transform.eulerAngles;
transform.eulerAngles = vector3s[3];
}
//impact:
if (percentage==0) {
transform.Translate(vector3s[1],space);
}
//transform.position=vector3s[0];
//reset:
if (isLocal) {
transform.localPosition=vector3s[0];
}else{
transform.position=vector3s[0];
}
//generate:
float diminishingControl = 1-percentage;
vector3s[2].x= UnityEngine.Random.Range(-vector3s[1].x*diminishingControl, vector3s[1].x*diminishingControl);
vector3s[2].y= UnityEngine.Random.Range(-vector3s[1].y*diminishingControl, vector3s[1].y*diminishingControl);
vector3s[2].z= UnityEngine.Random.Range(-vector3s[1].z*diminishingControl, vector3s[1].z*diminishingControl);
//apply:
//transform.Translate(vector3s[2],space);
if (isLocal) {
transform.localPosition+=vector3s[2];
}else{
transform.position+=vector3s[2];
}
//reset rotation:
if(tweenArguments.Contains("looktarget")){
transform.eulerAngles = currentRotation;
}
//need physics?
postUpdate=transform.position;
if(physics){
transform.position=preUpdate;
rigidbody.MovePosition(postUpdate);
}
}
void ApplyShakeScaleTargets(){
//impact:
if (percentage==0) {
transform.localScale=vector3s[1];
}
//reset:
transform.localScale=vector3s[0];
//generate:
float diminishingControl = 1-percentage;
vector3s[2].x= UnityEngine.Random.Range(-vector3s[1].x*diminishingControl, vector3s[1].x*diminishingControl);
vector3s[2].y= UnityEngine.Random.Range(-vector3s[1].y*diminishingControl, vector3s[1].y*diminishingControl);
vector3s[2].z= UnityEngine.Random.Range(-vector3s[1].z*diminishingControl, vector3s[1].z*diminishingControl);
//apply:
transform.localScale+=vector3s[2];
}
void ApplyShakeRotationTargets(){
preUpdate = transform.eulerAngles;
//impact:
if (percentage==0) {
transform.Rotate(vector3s[1],space);
}
//reset:
transform.eulerAngles=vector3s[0];
//generate:
float diminishingControl = 1-percentage;
vector3s[2].x= UnityEngine.Random.Range(-vector3s[1].x*diminishingControl, vector3s[1].x*diminishingControl);
vector3s[2].y= UnityEngine.Random.Range(-vector3s[1].y*diminishingControl, vector3s[1].y*diminishingControl);
vector3s[2].z= UnityEngine.Random.Range(-vector3s[1].z*diminishingControl, vector3s[1].z*diminishingControl);
//apply:
transform.Rotate(vector3s[2],space);
//need physics?
postUpdate=transform.eulerAngles;
if(physics){
transform.eulerAngles=preUpdate;
rigidbody.MoveRotation(Quaternion.Euler(postUpdate));
}
}
void ApplyPunchPositionTargets(){
preUpdate = transform.position;
//reset rotation to prevent look interferences as object rotates and attempts to move with translate and record current rotation
Vector3 currentRotation = new Vector3();
if(tweenArguments.Contains("looktarget")){
currentRotation = transform.eulerAngles;
transform.eulerAngles = vector3s[4];
}
//calculate:
if(vector3s[1].x>0){
vector3s[2].x = punch(vector3s[1].x,percentage);
}else if(vector3s[1].x<0){
vector3s[2].x=-punch(Mathf.Abs(vector3s[1].x),percentage);
}
if(vector3s[1].y>0){
vector3s[2].y=punch(vector3s[1].y,percentage);
}else if(vector3s[1].y<0){
vector3s[2].y=-punch(Mathf.Abs(vector3s[1].y),percentage);
}
if(vector3s[1].z>0){
vector3s[2].z=punch(vector3s[1].z,percentage);
}else if(vector3s[1].z<0){
vector3s[2].z=-punch(Mathf.Abs(vector3s[1].z),percentage);
}
//apply:
transform.Translate(vector3s[2]-vector3s[3],space);
//record:
vector3s[3]=vector3s[2];
//reset rotation:
if(tweenArguments.Contains("looktarget")){
transform.eulerAngles = currentRotation;
}
//dial in:
/*
if(percentage==1){
transform.position=vector3s[0];
}
*/
//need physics?
postUpdate=transform.position;
if(physics){
transform.position=preUpdate;
rigidbody.MovePosition(postUpdate);
}
}
void ApplyPunchRotationTargets(){
preUpdate = transform.eulerAngles;
//calculate:
if(vector3s[1].x>0){
vector3s[2].x = punch(vector3s[1].x,percentage);
}else if(vector3s[1].x<0){
vector3s[2].x=-punch(Mathf.Abs(vector3s[1].x),percentage);
}
if(vector3s[1].y>0){
vector3s[2].y=punch(vector3s[1].y,percentage);
}else if(vector3s[1].y<0){
vector3s[2].y=-punch(Mathf.Abs(vector3s[1].y),percentage);
}
if(vector3s[1].z>0){
vector3s[2].z=punch(vector3s[1].z,percentage);
}else if(vector3s[1].z<0){
vector3s[2].z=-punch(Mathf.Abs(vector3s[1].z),percentage);
}
//apply:
transform.Rotate(vector3s[2]-vector3s[3],space);
//record:
vector3s[3]=vector3s[2];
//dial in:
/*
if(percentage==1){
transform.eulerAngles=vector3s[0];
}
*/
//need physics?
postUpdate=transform.eulerAngles;
if(physics){
transform.eulerAngles=preUpdate;
rigidbody.MoveRotation(Quaternion.Euler(postUpdate));
}
}
void ApplyPunchScaleTargets(){
//calculate:
if(vector3s[1].x>0){
vector3s[2].x = punch(vector3s[1].x,percentage);
}else if(vector3s[1].x<0){
vector3s[2].x=-punch(Mathf.Abs(vector3s[1].x),percentage);
}
if(vector3s[1].y>0){
vector3s[2].y=punch(vector3s[1].y,percentage);
}else if(vector3s[1].y<0){
vector3s[2].y=-punch(Mathf.Abs(vector3s[1].y),percentage);
}
if(vector3s[1].z>0){
vector3s[2].z=punch(vector3s[1].z,percentage);
}else if(vector3s[1].z<0){
vector3s[2].z=-punch(Mathf.Abs(vector3s[1].z),percentage);
}
//apply:
transform.localScale=vector3s[0]+vector3s[2];
//dial in:
/*
if(percentage==1){
transform.localScale=vector3s[0];
}
*/
}
#endregion
#region #5 Tween Steps
IEnumerator TweenDelay(){
delayStarted = Time.time;
yield return new WaitForSeconds (delay);
if(wasPaused){
wasPaused=false;
TweenStart();
}
}
void TweenStart(){
CallBack("onstart");
if(!loop){//only if this is not a loop
ConflictCheck();
GenerateTargets();
}
//run stab:
if(type == "stab"){
audioSource.PlayOneShot(audioSource.clip);
}
//toggle isKinematic for iTweens that may interfere with physics:
if (type == "move" || type=="scale" || type=="rotate" || type=="punch" || type=="shake" || type=="curve" || type=="look") {
EnableKinematic();
}
isRunning = true;
}
IEnumerator TweenRestart(){
if(delay > 0){
delayStarted = Time.time;
yield return new WaitForSeconds (delay);
}
loop=true;
TweenStart();
}
void TweenUpdate(){
apply();
CallBack("onupdate");
UpdatePercentage();
}
void TweenComplete(){
isRunning=false;
//dial in percentage to 1 or 0 for final run:
if(percentage>.5f){
percentage=1f;
}else{
percentage=0;
}
//apply dial in and final run:
apply();
if(type == "value"){
CallBack("onupdate"); //CallBack run for ValueTo since it only calculates and applies in the update callback
}
//loop or dispose?
if(loopType==LoopType.none){
Dispose();
}else{
TweenLoop();
}
CallBack("oncomplete");
}
void TweenLoop(){
DisableKinematic(); //give physics control again
switch(loopType){
case LoopType.loop:
//rewind:
percentage=0;
runningTime=0;
apply();
//replay:
StartCoroutine("TweenRestart");
break;
case LoopType.pingPong:
reverse = !reverse;
runningTime=0;
//replay:
StartCoroutine("TweenRestart");
break;
}
}
#endregion
#region #6 Update Callable
/// <summary>
/// Returns a Rect that is eased between a current and target value by the supplied speed.
/// </summary>
/// <returns>
/// A <see cref="Rect"/
/// </returns>
/// <param name='currentValue'>
/// A <see cref="Rect"/> the starting or initial value
/// </param>
/// <param name='targetValue'>
/// A <see cref="Rect"/> the target value that the current value will be eased to.
/// </param>
/// <param name='speed'>
/// A <see cref="System.Single"/> to be used as rate of speed (larger number equals faster animation)
/// </param>
public static Rect RectUpdate(Rect currentValue, Rect targetValue, float speed){
Rect diff = new Rect(FloatUpdate(currentValue.x, targetValue.x, speed), FloatUpdate(currentValue.y, targetValue.y, speed), FloatUpdate(currentValue.width, targetValue.width, speed), FloatUpdate(currentValue.height, targetValue.height, speed));
return (diff);
}
/// <summary>
/// Returns a Vector3 that is eased between a current and target value by the supplied speed.
/// </summary>
/// <returns>
/// A <see cref="Vector3"/>
/// </returns>
/// <param name='currentValue'>
/// A <see cref="Vector3"/> the starting or initial value
/// </param>
/// <param name='targetValue'>
/// A <see cref="Vector3"/> the target value that the current value will be eased to.
/// </param>
/// <param name='speed'>
/// A <see cref="System.Single"/> to be used as rate of speed (larger number equals faster animation)
/// </param>
public static Vector3 Vector3Update(Vector3 currentValue, Vector3 targetValue, float speed){
Vector3 diff = targetValue - currentValue;
currentValue += (diff * speed) * Time.deltaTime;
return (currentValue);
}
/// <summary>
/// Returns a Vector2 that is eased between a current and target value by the supplied speed.
/// </summary>
/// <returns>
/// A <see cref="Vector2"/>
/// </returns>
/// <param name='currentValue'>
/// A <see cref="Vector2"/> the starting or initial value
/// </param>
/// <param name='targetValue'>
/// A <see cref="Vector2"/> the target value that the current value will be eased to.
/// </param>
/// <param name='speed'>
/// A <see cref="System.Single"/> to be used as rate of speed (larger number equals faster animation)
/// </param>
public static Vector2 Vector2Update(Vector2 currentValue, Vector2 targetValue, float speed){
Vector2 diff = targetValue - currentValue;
currentValue += (diff * speed) * Time.deltaTime;
return (currentValue);
}
/// <summary>
/// Returns a float that is eased between a current and target value by the supplied speed.
/// </summary>
/// <returns>
/// A <see cref="System.Single"/>
/// </returns>
/// <param name='currentValue'>
/// A <see cref="System.Single"/> the starting or initial value
/// </param>
/// <param name='targetValue'>
/// A <see cref="System.Single"/> the target value that the current value will be eased to.
/// </param>
/// <param name='speed'>
/// A <see cref="System.Single"/> to be used as rate of speed (larger number equals faster animation)
/// </param>
public static float FloatUpdate(float currentValue, float targetValue, float speed){
float diff = targetValue - currentValue;
currentValue += (diff * speed) * Time.deltaTime;
return (currentValue);
}
/// <summary>
/// Similar to FadeTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="alpha">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the final alpha value of the animation.
/// </param>
/// <param name="includechildren">
/// A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
public static void FadeUpdate(GameObject target, Hashtable args){
args["a"]=args["alpha"];
ColorUpdate(target,args);
}
/// <summary>
/// Similar to FadeTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with MINIMUM customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="alpha">
/// A <see cref="System.Single"/> for the final alpha value of the animation.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void FadeUpdate(GameObject target, float alpha, float time){
FadeUpdate(target,Hash("alpha",alpha,"time",time));
}
/// <summary>
/// Similar to ColorTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="color">
/// A <see cref="Color"/> to change the GameObject's color to.
/// </param>
/// <param name="r">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color red.
/// </param>
/// <param name="g">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
/// </param>
/// <param name="b">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
/// </param>
/// <param name="a">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the alpha.
/// </param>
/// <param name="namedcolorvalue">
/// A <see cref="NamedColorValue"/> or <see cref="System.String"/> for the individual setting of the alpha.
/// </param>
/// <param name="includechildren">
/// A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ColorUpdate(GameObject target, Hashtable args){
CleanArgs(args);
float time;
Color[] colors = new Color[4];
//handle children:
if(!args.Contains("includechildren") || (bool)args["includechildren"]){
foreach(Transform child in target.transform){
ColorUpdate(child.gameObject,args);
}
}
//set smooth time:
if(args.Contains("time")){
time=(float)args["time"];
time*=Defaults.updateTimePercentage;
}else{
time=Defaults.updateTime;
}
//init values:
if(target.GetComponent(typeof(GUITexture))){
colors[0] = colors[1] = target.guiTexture.color;
}else if(target.GetComponent(typeof(GUIText))){
colors[0] = colors[1] = target.guiText.material.color;
}else if(target.renderer){
colors[0] = colors[1] = target.renderer.material.color;
}else if(target.light){
colors[0] = colors[1] = target.light.color;
}
//to values:
if (args.Contains("color")) {
colors[1]=(Color)args["color"];
}else{
if (args.Contains("r")) {
colors[1].r=(float)args["r"];
}
if (args.Contains("g")) {
colors[1].g=(float)args["g"];
}
if (args.Contains("b")) {
colors[1].b=(float)args["b"];
}
if (args.Contains("a")) {
colors[1].a=(float)args["a"];
}
}
//calculate:
colors[3].r=Mathf.SmoothDamp(colors[0].r,colors[1].r,ref colors[2].r,time);
colors[3].g=Mathf.SmoothDamp(colors[0].g,colors[1].g,ref colors[2].g,time);
colors[3].b=Mathf.SmoothDamp(colors[0].b,colors[1].b,ref colors[2].b,time);
colors[3].a=Mathf.SmoothDamp(colors[0].a,colors[1].a,ref colors[2].a,time);
//apply:
if(target.GetComponent(typeof(GUITexture))){
target.guiTexture.color=colors[3];
}else if(target.GetComponent(typeof(GUIText))){
target.guiText.material.color=colors[3];
}else if(target.renderer){
target.renderer.material.color=colors[3];
}else if(target.light){
target.light.color=colors[3];
}
}
/// <summary>
/// Similar to ColorTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with MINIMUM customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="color">
/// A <see cref="Color"/> to change the GameObject's color to.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ColorUpdate(GameObject target, Color color, float time){
ColorUpdate(target,Hash("color",color,"time",time));
}
/// <summary>
/// Similar to AudioTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="audiosource">
/// A <see cref="AudioSource"/> for which AudioSource to use.
/// </param>
/// <param name="volume">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the target level of volume.
/// </param>
/// <param name="pitch">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the target pitch.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
public static void AudioUpdate(GameObject target, Hashtable args){
CleanArgs(args);
AudioSource audioSource;
float time;
Vector2[] vector2s = new Vector2[4];
//set smooth time:
if(args.Contains("time")){
time=(float)args["time"];
time*=Defaults.updateTimePercentage;
}else{
time=Defaults.updateTime;
}
//set audioSource:
if(args.Contains("audiosource")){
audioSource=(AudioSource)args["audiosource"];
}else{
if(target.GetComponent(typeof(AudioSource))){
audioSource=target.audio;
}else{
//throw error if no AudioSource is available:
Debug.LogError("iTween Error: AudioUpdate requires an AudioSource.");
return;
}
}
//from values:
vector2s[0] = vector2s[1] = new Vector2(audioSource.volume,audioSource.pitch);
//set to:
if(args.Contains("volume")){
vector2s[1].x=(float)args["volume"];
}
if(args.Contains("pitch")){
vector2s[1].y=(float)args["pitch"];
}
//calculate:
vector2s[3].x=Mathf.SmoothDampAngle(vector2s[0].x,vector2s[1].x,ref vector2s[2].x,time);
vector2s[3].y=Mathf.SmoothDampAngle(vector2s[0].y,vector2s[1].y,ref vector2s[2].y,time);
//apply:
audioSource.volume=vector2s[3].x;
audioSource.pitch=vector2s[3].y;
}
/// <summary>
/// Similar to AudioTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with MINIMUM customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="volume">
/// A <see cref="System.Single"/> for the target level of volume.
/// </param>
/// <param name="pitch">
/// A <see cref="System.Single"/> for the target pitch.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void AudioUpdate(GameObject target, float volume, float pitch, float time){
AudioUpdate(target,Hash("volume",volume,"pitch",pitch,"time",time));
}
/// <summary>
/// Similar to RotateTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="rotation">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for the target Euler angles in degrees to rotate to.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="islocal">
/// A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
public static void RotateUpdate(GameObject target, Hashtable args){
CleanArgs(args);
bool isLocal;
float time;
Vector3[] vector3s = new Vector3[4];
Vector3 preUpdate = target.transform.eulerAngles;
//set smooth time:
if(args.Contains("time")){
time=(float)args["time"];
time*=Defaults.updateTimePercentage;
}else{
time=Defaults.updateTime;
}
//set isLocal:
if(args.Contains("islocal")){
isLocal = (bool)args["islocal"];
}else{
isLocal = Defaults.isLocal;
}
//from values:
if(isLocal){
vector3s[0] = target.transform.localEulerAngles;
}else{
vector3s[0] = target.transform.eulerAngles;
}
//set to:
if(args.Contains("rotation")){
if (args["rotation"].GetType() == typeof(Transform)){
Transform trans = (Transform)args["rotation"];
vector3s[1]=trans.eulerAngles;
}else if(args["rotation"].GetType() == typeof(Vector3)){
vector3s[1]=(Vector3)args["rotation"];
}
}
//calculate:
vector3s[3].x=Mathf.SmoothDampAngle(vector3s[0].x,vector3s[1].x,ref vector3s[2].x,time);
vector3s[3].y=Mathf.SmoothDampAngle(vector3s[0].y,vector3s[1].y,ref vector3s[2].y,time);
vector3s[3].z=Mathf.SmoothDampAngle(vector3s[0].z,vector3s[1].z,ref vector3s[2].z,time);
//apply:
if(isLocal){
target.transform.localEulerAngles=vector3s[3];
}else{
target.transform.eulerAngles=vector3s[3];
}
//need physics?
if(target.rigidbody != null){
Vector3 postUpdate=target.transform.eulerAngles;
target.transform.eulerAngles=preUpdate;
target.rigidbody.MoveRotation(Quaternion.Euler(postUpdate));
}
}
/// <summary>
/// Similar to RotateTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with MINIMUM customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="rotation">
/// A <see cref="Vector3"/> for the target Euler angles in degrees to rotate to.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void RotateUpdate(GameObject target, Vector3 rotation, float time){
RotateUpdate(target,Hash("rotation",rotation,"time",time));
}
/// <summary>
/// Similar to ScaleTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="scale">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for the final scale.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ScaleUpdate(GameObject target, Hashtable args){
CleanArgs(args);
float time;
Vector3[] vector3s = new Vector3[4];
//set smooth time:
if(args.Contains("time")){
time=(float)args["time"];
time*=Defaults.updateTimePercentage;
}else{
time=Defaults.updateTime;
}
//init values:
vector3s[0] = vector3s[1] = target.transform.localScale;
//to values:
if (args.Contains("scale")) {
if (args["scale"].GetType() == typeof(Transform)){
Transform trans = (Transform)args["scale"];
vector3s[1]=trans.localScale;
}else if(args["scale"].GetType() == typeof(Vector3)){
vector3s[1]=(Vector3)args["scale"];
}
}else{
if (args.Contains("x")) {
vector3s[1].x=(float)args["x"];
}
if (args.Contains("y")) {
vector3s[1].y=(float)args["y"];
}
if (args.Contains("z")) {
vector3s[1].z=(float)args["z"];
}
}
//calculate:
vector3s[3].x=Mathf.SmoothDamp(vector3s[0].x,vector3s[1].x,ref vector3s[2].x,time);
vector3s[3].y=Mathf.SmoothDamp(vector3s[0].y,vector3s[1].y,ref vector3s[2].y,time);
vector3s[3].z=Mathf.SmoothDamp(vector3s[0].z,vector3s[1].z,ref vector3s[2].z,time);
//apply:
target.transform.localScale=vector3s[3];
}
/// <summary>
/// Similar to ScaleTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with MINIMUM customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="scale">
/// A <see cref="Vector3"/> for the final scale.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void ScaleUpdate(GameObject target, Vector3 scale, float time){
ScaleUpdate(target,Hash("scale",scale,"time",time));
}
/// <summary>
/// Similar to MoveTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="position">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for a point in space the GameObject will animate to.
/// </param>
/// <param name="x">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.
/// </param>
/// <param name="y">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.
/// </param>
/// <param name="z">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
/// <param name="islocal">
/// A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.
/// </param>
/// <param name="orienttopath">
/// A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.
/// </param>
/// <param name="looktime">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".
/// </param>
/// <param name="axis">
/// A <see cref="System.String"/>. Restricts rotation to the supplied axis only.
/// </param>
public static void MoveUpdate(GameObject target, Hashtable args){
CleanArgs(args);
float time;
Vector3[] vector3s = new Vector3[4];
bool isLocal;
Vector3 preUpdate = target.transform.position;
//set smooth time:
if(args.Contains("time")){
time=(float)args["time"];
time*=Defaults.updateTimePercentage;
}else{
time=Defaults.updateTime;
}
//set isLocal:
if(args.Contains("islocal")){
isLocal = (bool)args["islocal"];
}else{
isLocal = Defaults.isLocal;
}
//init values:
if(isLocal){
vector3s[0] = vector3s[1] = target.transform.localPosition;
}else{
vector3s[0] = vector3s[1] = target.transform.position;
}
//to values:
if (args.Contains("position")) {
if (args["position"].GetType() == typeof(Transform)){
Transform trans = (Transform)args["position"];
vector3s[1]=trans.position;
}else if(args["position"].GetType() == typeof(Vector3)){
vector3s[1]=(Vector3)args["position"];
}
}else{
if (args.Contains("x")) {
vector3s[1].x=(float)args["x"];
}
if (args.Contains("y")) {
vector3s[1].y=(float)args["y"];
}
if (args.Contains("z")) {
vector3s[1].z=(float)args["z"];
}
}
//calculate:
vector3s[3].x=Mathf.SmoothDamp(vector3s[0].x,vector3s[1].x,ref vector3s[2].x,time);
vector3s[3].y=Mathf.SmoothDamp(vector3s[0].y,vector3s[1].y,ref vector3s[2].y,time);
vector3s[3].z=Mathf.SmoothDamp(vector3s[0].z,vector3s[1].z,ref vector3s[2].z,time);
//handle orient to path:
if(args.Contains("orienttopath") && (bool)args["orienttopath"]){
args["looktarget"] = vector3s[3];
}
//look applications:
if(args.Contains("looktarget")){
iTween.LookUpdate(target,args);
}
//apply:
if(isLocal){
target.transform.localPosition = vector3s[3];
}else{
target.transform.position=vector3s[3];
}
//need physics?
if(target.rigidbody != null){
Vector3 postUpdate=target.transform.position;
target.transform.position=preUpdate;
target.rigidbody.MovePosition(postUpdate);
}
}
/// <summary>
/// Similar to MoveTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with MINIMUM customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="position">
/// A <see cref="Vector3"/> for a point in space the GameObject will animate to.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void MoveUpdate(GameObject target, Vector3 position, float time){
MoveUpdate(target,Hash("position",position,"time",time));
}
/// <summary>
/// Similar to LookTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="looktarget">
/// A <see cref="Transform"/> or <see cref="Vector3"/> for a target the GameObject will look at.
/// </param>
/// <param name="axis">
/// A <see cref="System.String"/>. Restricts rotation to the supplied axis only.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
/// </param>
public static void LookUpdate(GameObject target, Hashtable args){
CleanArgs(args);
float time;
Vector3[] vector3s = new Vector3[5];
//set smooth time:
if(args.Contains("looktime")){
time=(float)args["looktime"];
time*=Defaults.updateTimePercentage;
}else if(args.Contains("time")){
time=(float)args["time"]*.15f;
time*=Defaults.updateTimePercentage;
}else{
time=Defaults.updateTime;
}
//from values:
vector3s[0] = target.transform.eulerAngles;
//set look:
if(args.Contains("looktarget")){
if (args["looktarget"].GetType() == typeof(Transform)) {
//target.transform.LookAt((Transform)args["looktarget"]);
target.transform.LookAt((Transform)args["looktarget"], (Vector3?)args["up"] ?? Defaults.up);
}else if(args["looktarget"].GetType() == typeof(Vector3)){
//target.transform.LookAt((Vector3)args["looktarget"]);
target.transform.LookAt((Vector3)args["looktarget"], (Vector3?)args["up"] ?? Defaults.up);
}
}else{
Debug.LogError("iTween Error: LookUpdate needs a 'looktarget' property!");
return;
}
//to values and reset look:
vector3s[1]=target.transform.eulerAngles;
target.transform.eulerAngles=vector3s[0];
//calculate:
vector3s[3].x=Mathf.SmoothDampAngle(vector3s[0].x,vector3s[1].x,ref vector3s[2].x,time);
vector3s[3].y=Mathf.SmoothDampAngle(vector3s[0].y,vector3s[1].y,ref vector3s[2].y,time);
vector3s[3].z=Mathf.SmoothDampAngle(vector3s[0].z,vector3s[1].z,ref vector3s[2].z,time);
//apply:
target.transform.eulerAngles=vector3s[3];
//axis restriction:
if(args.Contains("axis")){
vector3s[4]=target.transform.eulerAngles;
switch((string)args["axis"]){
case "x":
vector3s[4].y=vector3s[0].y;
vector3s[4].z=vector3s[0].z;
break;
case "y":
vector3s[4].x=vector3s[0].x;
vector3s[4].z=vector3s[0].z;
break;
case "z":
vector3s[4].x=vector3s[0].x;
vector3s[4].y=vector3s[0].y;
break;
}
//apply axis restriction:
target.transform.eulerAngles=vector3s[4];
}
}
/// <summary>
/// Similar to LookTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/> to be the target of the animation.
/// </param>
/// <param name="looktarget">
/// A <see cref="Vector3"/> for a target the GameObject will look at.
/// </param>
/// <param name="time">
/// A <see cref="System.Single"/> for the time in seconds the animation will take to complete.
/// </param>
public static void LookUpdate(GameObject target, Vector3 looktarget, float time){
LookUpdate(target,Hash("looktarget",looktarget,"time",time));
}
#endregion
#region #7 External Utilities
/// <summary>
/// Returns the length of a curved path drawn through the provided array of Transforms.
/// </summary>
/// <returns>
/// A <see cref="System.Single"/>
/// </returns>
/// <param name='path'>
/// A <see cref="Transform[]"/>
/// </param>
public static float PathLength(Transform[] path){
Vector3[] suppliedPath = new Vector3[path.Length];
float pathLength = 0;
//create and store path points:
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
Vector3[] vector3s = PathControlPointGenerator(suppliedPath);
//Line Draw:
Vector3 prevPt = Interp(vector3s,0);
int SmoothAmount = path.Length*20;
for (int i = 1; i <= SmoothAmount; i++) {
float pm = (float) i / SmoothAmount;
Vector3 currPt = Interp(vector3s,pm);
pathLength += Vector3.Distance(prevPt,currPt);
prevPt = currPt;
}
return pathLength;
}
/// <summary>
/// Returns the length of a curved path drawn through the provided array of Vector3s.
/// </summary>
/// <returns>
/// The length.
/// </returns>
/// <param name='path'>
/// A <see cref="Vector3[]"/>
/// </param>
public static float PathLength(Vector3[] path){
float pathLength = 0;
Vector3[] vector3s = PathControlPointGenerator(path);
//Line Draw:
Vector3 prevPt = Interp(vector3s,0);
int SmoothAmount = path.Length*20;
for (int i = 1; i <= SmoothAmount; i++) {
float pm = (float) i / SmoothAmount;
Vector3 currPt = Interp(vector3s,pm);
pathLength += Vector3.Distance(prevPt,currPt);
prevPt = currPt;
}
return pathLength;
}
/// <summary>
/// Creates and returns a full-screen Texture2D for use with CameraFade.
/// </summary>
/// <returns>
/// Texture2D
/// </returns>
/// <param name='color'>
/// Color
/// </param>
public static Texture2D CameraTexture(Color color){
Texture2D texture = new Texture2D(Screen.width,Screen.height,TextureFormat.ARGB32, false);
Color[] colors = new Color[Screen.width*Screen.height];
for (int i = 0; i < colors.Length; i++) {
colors[i]=color;
}
texture.SetPixels(colors);
texture.Apply();
return(texture);
}
/// <summary>
/// Puts a GameObject on a path at the provided percentage
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/>
/// </param>
/// <param name="path">
/// A <see cref="Vector3[]"/>
/// </param>
/// <param name="percent">
/// A <see cref="System.Single"/>
/// </param>
public static void PutOnPath(GameObject target, Vector3[] path, float percent){
target.transform.position=Interp(PathControlPointGenerator(path),percent);
}
/// <summary>
/// Puts a GameObject on a path at the provided percentage
/// </summary>
/// <param name="target">
/// A <see cref="Transform"/>
/// </param>
/// <param name="path">
/// A <see cref="Vector3[]"/>
/// </param>
/// <param name="percent">
/// A <see cref="System.Single"/>
/// </param>
public static void PutOnPath(Transform target, Vector3[] path, float percent){
target.position=Interp(PathControlPointGenerator(path),percent);
}
/// <summary>
/// Puts a GameObject on a path at the provided percentage
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/>
/// </param>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="percent">
/// A <see cref="System.Single"/>
/// </param>
public static void PutOnPath(GameObject target, Transform[] path, float percent){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
target.transform.position=Interp(PathControlPointGenerator(suppliedPath),percent);
}
/// <summary>
/// Puts a GameObject on a path at the provided percentage
/// </summary>
/// <param name="target">
/// A <see cref="Transform"/>
/// </param>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="percent">
/// A <see cref="System.Single"/>
/// </param>
public static void PutOnPath(Transform target, Transform[] path, float percent){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
target.position=Interp(PathControlPointGenerator(suppliedPath),percent);
}
/// <summary>
/// Returns a Vector3 position on a path at the provided percentage
/// </summary>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="percent">
/// A <see cref="System.Single"/>
/// </param>
/// <returns>
/// A <see cref="Vector3"/>
/// </returns>
public static Vector3 PointOnPath(Transform[] path, float percent){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
return(Interp(PathControlPointGenerator(suppliedPath),percent));
}
/// <summary>
/// When called from an OnDrawGizmos() function it will draw a line through the provided array of Vector3s.
/// </summary>
/// <param name="line">
/// A <see cref="Vector3s[]"/>
/// </param>
public static void DrawLine(Vector3[] line) {
if(line.Length>0){
DrawLineHelper(line,Defaults.color,"gizmos");
}
}
/// <summary>
/// When called from an OnDrawGizmos() function it will draw a line through the provided array of Vector3s.
/// </summary>
/// <param name="line">
/// A <see cref="Vector3s[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawLine(Vector3[] line, Color color) {
if(line.Length>0){
DrawLineHelper(line,color,"gizmos");
}
}
/// <summary>
/// When called from an OnDrawGizmos() function it will draw a line through the provided array of Transforms.
/// </summary>
/// <param name="line">
/// A <see cref="Transform[]"/>
/// </param>
public static void DrawLine(Transform[] line) {
if(line.Length>0){
//create and store line points:
Vector3[] suppliedLine = new Vector3[line.Length];
for (int i = 0; i < line.Length; i++) {
suppliedLine[i]=line[i].position;
}
DrawLineHelper(suppliedLine,Defaults.color,"gizmos");
}
}
/// <summary>
/// When called from an OnDrawGizmos() function it will draw a line through the provided array of Transforms.
/// </summary>
/// <param name="line">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawLine(Transform[] line,Color color) {
if(line.Length>0){
//create and store line points:
Vector3[] suppliedLine = new Vector3[line.Length];
for (int i = 0; i < line.Length; i++) {
suppliedLine[i]=line[i].position;
}
DrawLineHelper(suppliedLine, color,"gizmos");
}
}
/// <summary>
/// Draws a line through the provided array of Vector3s with Gizmos.DrawLine().
/// </summary>
/// <param name="line">
/// A <see cref="Vector3s[]"/>
/// </param>
public static void DrawLineGizmos(Vector3[] line) {
if(line.Length>0){
DrawLineHelper(line,Defaults.color,"gizmos");
}
}
/// <summary>
/// Draws a line through the provided array of Vector3s with Gizmos.DrawLine().
/// </summary>
/// <param name="line">
/// A <see cref="Vector3s[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawLineGizmos(Vector3[] line, Color color) {
if(line.Length>0){
DrawLineHelper(line,color,"gizmos");
}
}
/// <summary>
/// Draws a line through the provided array of Transforms with Gizmos.DrawLine().
/// </summary>
/// <param name="line">
/// A <see cref="Transform[]"/>
/// </param>
public static void DrawLineGizmos(Transform[] line) {
if(line.Length>0){
//create and store line points:
Vector3[] suppliedLine = new Vector3[line.Length];
for (int i = 0; i < line.Length; i++) {
suppliedLine[i]=line[i].position;
}
DrawLineHelper(suppliedLine,Defaults.color,"gizmos");
}
}
/// <summary>
/// Draws a line through the provided array of Transforms with Gizmos.DrawLine().
/// </summary>
/// <param name="line">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawLineGizmos(Transform[] line,Color color) {
if(line.Length>0){
//create and store line points:
Vector3[] suppliedLine = new Vector3[line.Length];
for (int i = 0; i < line.Length; i++) {
suppliedLine[i]=line[i].position;
}
DrawLineHelper(suppliedLine, color,"gizmos");
}
}
/// <summary>
/// Draws a line through the provided array of Vector3s with Handles.DrawLine().
/// </summary>
/// <param name="line">
/// A <see cref="Vector3s[]"/>
/// </param>
public static void DrawLineHandles(Vector3[] line) {
if(line.Length>0){
DrawLineHelper(line,Defaults.color,"handles");
}
}
/// <summary>
/// Draws a line through the provided array of Vector3s with Handles.DrawLine().
/// </summary>
/// <param name="line">
/// A <see cref="Vector3s[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawLineHandles(Vector3[] line, Color color) {
if(line.Length>0){
DrawLineHelper(line,color,"handles");
}
}
/// <summary>
/// Draws a line through the provided array of Transforms with Handles.DrawLine().
/// </summary>
/// <param name="line">
/// A <see cref="Transform[]"/>
/// </param>
public static void DrawLineHandles(Transform[] line) {
if(line.Length>0){
//create and store line points:
Vector3[] suppliedLine = new Vector3[line.Length];
for (int i = 0; i < line.Length; i++) {
suppliedLine[i]=line[i].position;
}
DrawLineHelper(suppliedLine,Defaults.color,"handles");
}
}
/// <summary>
/// Draws a line through the provided array of Transforms with Handles.DrawLine().
/// </summary>
/// <param name="line">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawLineHandles(Transform[] line,Color color) {
if(line.Length>0){
//create and store line points:
Vector3[] suppliedLine = new Vector3[line.Length];
for (int i = 0; i < line.Length; i++) {
suppliedLine[i]=line[i].position;
}
DrawLineHelper(suppliedLine, color,"handles");
}
}
/// <summary>
/// Returns a Vector3 position on a path at the provided percentage
/// </summary>
/// <param name="path">
/// A <see cref="Vector3[]"/>
/// </param>
/// <param name="percent">
/// A <see cref="System.Single"/>
/// </param>
/// <returns>
/// A <see cref="Vector3"/>
/// </returns>
public static Vector3 PointOnPath(Vector3[] path, float percent){
return(Interp(PathControlPointGenerator(path),percent));
}
/// <summary>
/// When called from an OnDrawGizmos() function it will draw a curved path through the provided array of Vector3s.
/// </summary>
/// <param name="path">
/// A <see cref="Vector3s[]"/>
/// </param>
public static void DrawPath(Vector3[] path) {
if(path.Length>0){
DrawPathHelper(path,Defaults.color,"gizmos");
}
}
/// <summary>
/// When called from an OnDrawGizmos() function it will draw a curved path through the provided array of Vector3s.
/// </summary>
/// <param name="path">
/// A <see cref="Vector3s[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawPath(Vector3[] path, Color color) {
if(path.Length>0){
DrawPathHelper(path, color,"gizmos");
}
}
/// <summary>
/// When called from an OnDrawGizmos() function it will draw a curved path through the provided array of Transforms.
/// </summary>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
public static void DrawPath(Transform[] path) {
if(path.Length>0){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
DrawPathHelper(suppliedPath,Defaults.color,"gizmos");
}
}
/// <summary>
/// When called from an OnDrawGizmos() function it will draw a curved path through the provided array of Transforms.
/// </summary>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawPath(Transform[] path,Color color) {
if(path.Length>0){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
DrawPathHelper(suppliedPath, color,"gizmos");
}
}
/// <summary>
/// Draws a curved path through the provided array of Vector3s with Gizmos.DrawLine().
/// </summary>
/// <param name="path">
/// A <see cref="Vector3s[]"/>
/// </param>
public static void DrawPathGizmos(Vector3[] path) {
if(path.Length>0){
DrawPathHelper(path,Defaults.color,"gizmos");
}
}
/// <summary>
/// Draws a curved path through the provided array of Vector3s with Gizmos.DrawLine().
/// </summary>
/// <param name="path">
/// A <see cref="Vector3s[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawPathGizmos(Vector3[] path, Color color) {
if(path.Length>0){
DrawPathHelper(path, color,"gizmos");
}
}
/// <summary>
/// Draws a curved path through the provided array of Transforms with Gizmos.DrawLine().
/// </summary>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
public static void DrawPathGizmos(Transform[] path) {
if(path.Length>0){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
DrawPathHelper(suppliedPath,Defaults.color,"gizmos");
}
}
/// <summary>
/// Draws a curved path through the provided array of Transforms with Gizmos.DrawLine().
/// </summary>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawPathGizmos(Transform[] path,Color color) {
if(path.Length>0){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
DrawPathHelper(suppliedPath, color,"gizmos");
}
}
/// <summary>
/// Draws a curved path through the provided array of Vector3s with Handles.DrawLine().
/// </summary>
/// <param name="path">
/// A <see cref="Vector3s[]"/>
/// </param>
public static void DrawPathHandles(Vector3[] path) {
if(path.Length>0){
DrawPathHelper(path,Defaults.color,"handles");
}
}
/// <summary>
/// Draws a curved path through the provided array of Vector3s with Handles.DrawLine().
/// </summary>
/// <param name="path">
/// A <see cref="Vector3s[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawPathHandles(Vector3[] path, Color color) {
if(path.Length>0){
DrawPathHelper(path, color,"handles");
}
}
/// <summary>
/// Draws a curved path through the provided array of Transforms with Handles.DrawLine().
/// </summary>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
public static void DrawPathHandles(Transform[] path) {
if(path.Length>0){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
DrawPathHelper(suppliedPath,Defaults.color,"handles");
}
}
/// <summary>
/// Draws a curved path through the provided array of Transforms with Handles.DrawLine().
/// </summary>
/// <param name="path">
/// A <see cref="Transform[]"/>
/// </param>
/// <param name="color">
/// A <see cref="Color"/>
/// </param>
public static void DrawPathHandles(Transform[] path,Color color) {
if(path.Length>0){
//create and store path points:
Vector3[] suppliedPath = new Vector3[path.Length];
for (int i = 0; i < path.Length; i++) {
suppliedPath[i]=path[i].position;
}
DrawPathHelper(suppliedPath, color,"handles");
}
}
/// <summary>
/// Changes a camera fade's texture.
/// </summary>
/// <param name="depth">
/// A <see cref="System.Int32"/>
/// </param>
public static void CameraFadeDepth(int depth){
if(cameraFade){
cameraFade.transform.position=new Vector3(cameraFade.transform.position.x,cameraFade.transform.position.y,depth);
}
}
/// <summary>
/// Removes and destroyes a camera fade.
/// </summary>
public static void CameraFadeDestroy(){
if(cameraFade){
Destroy(cameraFade);
}
}
/// <summary>
/// Changes a camera fade's texture.
/// </summary>
/// <param name='texture'>
/// A <see cref="Texture2D"/>
/// </param>
public static void CameraFadeSwap(Texture2D texture){
if(cameraFade){
cameraFade.guiTexture.texture=texture;
}
}
/// <summary>
/// Creates a GameObject (if it doesn't exist) at the supplied depth that can be used to simulate a camera fade.
/// </summary>
/// <param name='texture'>
/// A <see cref="Texture2D"/>
/// </param>
/// <param name='depth'>
/// A <see cref="System.Int32"/>
/// </param>
/// <returns>
/// A <see cref="GameObject"/> for a reference to the CameraFade.
/// </returns>
public static GameObject CameraFadeAdd(Texture2D texture, int depth){
if(cameraFade){
return null;
}else{
//establish colorFade object:
cameraFade = new GameObject("iTween Camera Fade");
cameraFade.transform.position= new Vector3(.5f,.5f,depth);
cameraFade.AddComponent("GUITexture");
cameraFade.guiTexture.texture=texture;
cameraFade.guiTexture.color = new Color(.5f,.5f,.5f,0);
return cameraFade;
}
}
/// <summary>
/// Creates a GameObject (if it doesn't exist) at the default depth that can be used to simulate a camera fade.
/// </summary>
/// <param name='texture'>
/// A <see cref="Texture2D"/>
/// </param>
/// <returns>
/// A <see cref="GameObject"/> for a reference to the CameraFade.
/// </returns>
public static GameObject CameraFadeAdd(Texture2D texture){
if(cameraFade){
return null;
}else{
//establish colorFade object:
cameraFade = new GameObject("iTween Camera Fade");
cameraFade.transform.position= new Vector3(.5f,.5f,Defaults.cameraFadeDepth);
cameraFade.AddComponent("GUITexture");
cameraFade.guiTexture.texture=texture;
cameraFade.guiTexture.color = new Color(.5f,.5f,.5f,0);
return cameraFade;
}
}
/// <summary>
/// Creates a GameObject (if it doesn't exist) at the default depth filled with black that can be used to simulate a camera fade.
/// </summary>
/// <returns>
/// A <see cref="GameObject"/> for a reference to the CameraFade.
/// </returns>
public static GameObject CameraFadeAdd(){
if(cameraFade){
return null;
}else{
//establish colorFade object:
cameraFade = new GameObject("iTween Camera Fade");
cameraFade.transform.position= new Vector3(.5f,.5f,Defaults.cameraFadeDepth);
cameraFade.AddComponent("GUITexture");
cameraFade.guiTexture.texture=CameraTexture(Color.black);
cameraFade.guiTexture.color = new Color(.5f,.5f,.5f,0);
return cameraFade;
}
}
//#################################
//# RESUME UTILITIES AND OVERLOADS #
//#################################
/// <summary>
/// Resume all iTweens on a GameObject.
/// </summary>
public static void Resume(GameObject target){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
item.enabled=true;
}
}
/// <summary>
/// Resume all iTweens on a GameObject including its children.
/// </summary>
public static void Resume(GameObject target, bool includechildren){
Resume(target);
if(includechildren){
foreach(Transform child in target.transform){
Resume(child.gameObject,true);
}
}
}
/// <summary>
/// Resume all iTweens on a GameObject of a particular type.
/// </summar
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to resume. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Resume(GameObject target, string type){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
item.enabled=true;
}
}
}
/// <summary>
/// Resume all iTweens on a GameObject of a particular type including its children.
/// </summar
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to resume. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Resume(GameObject target, string type, bool includechildren){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
item.enabled=true;
}
}
if(includechildren){
foreach(Transform child in target.transform){
Resume(child.gameObject,type,true);
}
}
}
/// <summary>
/// Resume all iTweens in scene.
/// </summary>
public static void Resume(){
for (int i = 0; i < tweens.Count; i++) {
Hashtable currentTween = (Hashtable)tweens[i];
GameObject target = (GameObject)currentTween["target"];
Resume(target);
}
}
/// <summary>
/// Resume all iTweens in scene of a particular type.
/// </summary>
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to resume. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Resume(string type){
ArrayList resumeArray = new ArrayList();
for (int i = 0; i < tweens.Count; i++) {
Hashtable currentTween = (Hashtable)tweens[i];
GameObject target = (GameObject)currentTween["target"];
resumeArray.Insert(resumeArray.Count,target);
}
for (int i = 0; i < resumeArray.Count; i++) {
Resume((GameObject)resumeArray[i],type);
}
}
//#################################
//# PAUSE UTILITIES AND OVERLOADS #
//#################################
/// <summary>
/// Pause all iTweens on a GameObject.
/// </summary>
public static void Pause(GameObject target){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
if(item.delay>0){
item.delay-=Time.time-item.delayStarted;
item.StopCoroutine("TweenDelay");
}
item.isPaused=true;
item.enabled=false;
}
}
/// <summary>
/// Pause all iTweens on a GameObject including its children.
/// </summary>
public static void Pause(GameObject target, bool includechildren){
Pause(target);
if(includechildren){
foreach(Transform child in target.transform){
Pause(child.gameObject,true);
}
}
}
/// <summary>
/// Pause all iTweens on a GameObject of a particular type.
/// </summar
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to pause. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Pause(GameObject target, string type){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
if(item.delay>0){
item.delay-=Time.time-item.delayStarted;
item.StopCoroutine("TweenDelay");
}
item.isPaused=true;
item.enabled=false;
}
}
}
/// <summary>
/// Pause all iTweens on a GameObject of a particular type including its children.
/// </summar
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to pause. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Pause(GameObject target, string type, bool includechildren){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
if(item.delay>0){
item.delay-=Time.time-item.delayStarted;
item.StopCoroutine("TweenDelay");
}
item.isPaused=true;
item.enabled=false;
}
}
if(includechildren){
foreach(Transform child in target.transform){
Pause(child.gameObject,type,true);
}
}
}
/// <summary>
/// Pause all iTweens in scene.
/// </summary>
public static void Pause(){
for (int i = 0; i < tweens.Count; i++) {
Hashtable currentTween = (Hashtable)tweens[i];
GameObject target = (GameObject)currentTween["target"];
Pause(target);
}
}
/// <summary>
/// Pause all iTweens in scene of a particular type.
/// </summary>
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to pause. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Pause(string type){
ArrayList pauseArray = new ArrayList();
for (int i = 0; i < tweens.Count; i++) {
Hashtable currentTween = (Hashtable)tweens[i];
GameObject target = (GameObject)currentTween["target"];
pauseArray.Insert(pauseArray.Count,target);
}
for (int i = 0; i < pauseArray.Count; i++) {
Pause((GameObject)pauseArray[i],type);
}
}
//#################################
//# COUNT UTILITIES AND OVERLOADS #
//#################################
/// <summary>
/// Count all iTweens in current scene.
/// </summary>
public static int Count(){
return(tweens.Count);
}
/// <summary>
/// Count all iTweens in current scene of a particular type.
/// </summary>
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to stop. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static int Count(string type){
int tweenCount = 0;
for (int i = 0; i < tweens.Count; i++) {
Hashtable currentTween = (Hashtable)tweens[i];
string targetType = (string)currentTween["type"]+(string)currentTween["method"];
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
tweenCount++;
}
}
return(tweenCount);
}
/// <summary>
/// Count all iTweens on a GameObject.
/// </summary>
public static int Count(GameObject target){
Component[] tweens = target.GetComponents(typeof(iTween));
return(tweens.Length);
}
/// <summary>
/// Count all iTweens on a GameObject of a particular type.
/// </summary>
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to count. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static int Count(GameObject target, string type){
int tweenCount = 0;
Component[] tweens = target.GetComponents(typeof(iTween));foreach (iTween item in tweens){
string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
tweenCount++;
}
}
return(tweenCount);
}
//################################
//# STOP UTILITIES AND OVERLOADS #
//################################
/// <summary>
/// Stop and destroy all Tweens in current scene.
/// </summary>
public static void Stop(){
for (int i = 0; i < tweens.Count; i++) {
Hashtable currentTween = (Hashtable)tweens[i];
GameObject target = (GameObject)currentTween["target"];
Stop(target);
}
tweens.Clear();
}
/// <summary>
/// Stop and destroy all iTweens in current scene of a particular type.
/// </summary>
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to stop. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Stop(string type){
ArrayList stopArray = new ArrayList();
for (int i = 0; i < tweens.Count; i++) {
Hashtable currentTween = (Hashtable)tweens[i];
GameObject target = (GameObject)currentTween["target"];
stopArray.Insert(stopArray.Count,target);
}
for (int i = 0; i < stopArray.Count; i++) {
Stop((GameObject)stopArray[i],type);
}
}
/* GFX47 MOD START */
/// <summary>
/// Stop and destroy all iTweens in current scene of a particular name.
/// </summary>
/// <param name="name">
/// The <see cref="System.String"/> name of iTween you would like to stop.
/// </param>
public static void StopByName(string name){
ArrayList stopArray = new ArrayList();
for (int i = 0; i < tweens.Count; i++) {
Hashtable currentTween = (Hashtable)tweens[i];
GameObject target = (GameObject)currentTween["target"];
stopArray.Insert(stopArray.Count,target);
}
for (int i = 0; i < stopArray.Count; i++) {
StopByName((GameObject)stopArray[i],name);
}
}
/* GFX47 MOD END */
/// <summary>
/// Stop and destroy all iTweens on a GameObject.
/// </summary>
public static void Stop(GameObject target){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
item.Dispose();
}
}
/// <summary>
/// Stop and destroy all iTweens on a GameObject including its children.
/// </summary>
public static void Stop(GameObject target, bool includechildren){
Stop(target);
if(includechildren){
foreach(Transform child in target.transform){
Stop(child.gameObject,true);
}
}
}
/// <summary>
/// Stop and destroy all iTweens on a GameObject of a particular type.
/// </summar
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to stop. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Stop(GameObject target, string type){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
item.Dispose();
}
}
}
/* GFX47 MOD START */
/// <summary>
/// Stop and destroy all iTweens on a GameObject of a particular name.
/// </summar
/// <param name="name">
/// The <see cref="System.String"/> name of iTween you would like to stop.
/// </param>
public static void StopByName(GameObject target, string name){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
/*string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
item.Dispose();
}*/
if(item._name == name){
item.Dispose();
}
}
}
/* GFX47 MOD END */
/// <summary>
/// Stop and destroy all iTweens on a GameObject of a particular type including its children.
/// </summar
/// <param name="type">
/// A <see cref="System.String"/> name of the type of iTween you would like to stop. Can be written as part of a name such as "mov" for all "MoveTo" iTweens.
/// </param>
public static void Stop(GameObject target, string type, bool includechildren){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
item.Dispose();
}
}
if(includechildren){
foreach(Transform child in target.transform){
Stop(child.gameObject,type,true);
}
}
}
/* GFX47 MOD START */
/// <summary>
/// Stop and destroy all iTweens on a GameObject of a particular name including its children.
/// </summar
/// <param name="name">
/// The <see cref="System.String"/> name of iTween you would like to stop.
/// </param>
public static void StopByName(GameObject target, string name, bool includechildren){
Component[] tweens = target.GetComponents(typeof(iTween));
foreach (iTween item in tweens){
/*string targetType = item.type+item.method;
targetType=targetType.Substring(0,type.Length);
if(targetType.ToLower() == type.ToLower()){
item.Dispose();
}*/
if(item._name == name){
item.Dispose();
}
}
if(includechildren){
foreach(Transform child in target.transform){
//Stop(child.gameObject,type,true);
StopByName(child.gameObject,name,true);
}
}
}
/* GFX47 MOD END */
/// <summary>
/// Universal interface to help in the creation of Hashtables. Especially useful for C# users.
/// </summary>
/// <param name="args">
/// A <see cref="System.Object[]"/> of alternating name value pairs. For example "time",1,"delay",2...
/// </param>
/// <returns>
/// A <see cref="Hashtable"/>
/// </returns>
public static Hashtable Hash(params object[] args){
Hashtable hashTable = new Hashtable(args.Length/2);
if (args.Length %2 != 0) {
Debug.LogError("Tween Error: Hash requires an even number of arguments!");
return null;
}else{
int i = 0;
while(i < args.Length - 1) {
hashTable.Add(args[i], args[i+1]);
i += 2;
}
return hashTable;
}
}
#endregion
#region Component Segments
void Awake(){
RetrieveArgs();
lastRealTime = Time.realtimeSinceStartup; // Added by PressPlay
}
IEnumerator Start(){
if(delay > 0){
yield return StartCoroutine("TweenDelay");
}
TweenStart();
}
//non-physics
void Update(){
if(isRunning && !physics){
if(!reverse){
if(percentage<1f){
TweenUpdate();
}else{
TweenComplete();
}
}else{
if(percentage>0){
TweenUpdate();
}else{
TweenComplete();
}
}
}
}
//physics
void FixedUpdate(){
if(isRunning && physics){
if(!reverse){
if(percentage<1f){
TweenUpdate();
}else{
TweenComplete();
}
}else{
if(percentage>0){
TweenUpdate();
}else{
TweenComplete();
}
}
}
}
void LateUpdate(){
//look applications:
if(tweenArguments.Contains("looktarget") && isRunning){
if(type =="move" || type =="shake" || type=="punch"){
LookUpdate(gameObject,tweenArguments);
}
}
}
void OnEnable(){
if(isRunning){
EnableKinematic();
}
//resume delay:
if(isPaused){
isPaused=false;
if(delay > 0){
wasPaused=true;
ResumeDelay();
}
}
}
void OnDisable(){
DisableKinematic();
}
#endregion
#region Internal Helpers
private static void DrawLineHelper(Vector3[] line, Color color, string method){
Gizmos.color=color;
for (int i = 0; i < line.Length-1; i++) {
if(method == "gizmos"){
Gizmos.DrawLine(line[i], line[i+1]);;
}else if(method == "handles"){
Debug.LogError("iTween Error: Drawing a line with Handles is temporarily disabled because of compatability issues with Unity 2.6!");
//UnityEditor.Handles.DrawLine(line[i], line[i+1]);
}
}
}
private static void DrawPathHelper(Vector3[] path, Color color, string method){
Vector3[] vector3s = PathControlPointGenerator(path);
//Line Draw:
Vector3 prevPt = Interp(vector3s,0);
Gizmos.color=color;
int SmoothAmount = path.Length*20;
for (int i = 1; i <= SmoothAmount; i++) {
float pm = (float) i / SmoothAmount;
Vector3 currPt = Interp(vector3s,pm);
if(method == "gizmos"){
Gizmos.DrawLine(currPt, prevPt);
}else if(method == "handles"){
Debug.LogError("iTween Error: Drawing a path with Handles is temporarily disabled because of compatability issues with Unity 2.6!");
//UnityEditor.Handles.DrawLine(currPt, prevPt);
}
prevPt = currPt;
}
}
private static Vector3[] PathControlPointGenerator(Vector3[] path){
Vector3[] suppliedPath;
Vector3[] vector3s;
//create and store path points:
suppliedPath = path;
//populate calculate path;
int offset = 2;
vector3s = new Vector3[suppliedPath.Length+offset];
Array.Copy(suppliedPath,0,vector3s,1,suppliedPath.Length);
//populate start and end control points:
//vector3s[0] = vector3s[1] - vector3s[2];
vector3s[0] = vector3s[1] + (vector3s[1] - vector3s[2]);
vector3s[vector3s.Length-1] = vector3s[vector3s.Length-2] + (vector3s[vector3s.Length-2] - vector3s[vector3s.Length-3]);
//is this a closed, continuous loop? yes? well then so let's make a continuous Catmull-Rom spline!
if(vector3s[1] == vector3s[vector3s.Length-2]){
Vector3[] tmpLoopSpline = new Vector3[vector3s.Length];
Array.Copy(vector3s,tmpLoopSpline,vector3s.Length);
tmpLoopSpline[0]=tmpLoopSpline[tmpLoopSpline.Length-3];
tmpLoopSpline[tmpLoopSpline.Length-1]=tmpLoopSpline[2];
vector3s=new Vector3[tmpLoopSpline.Length];
Array.Copy(tmpLoopSpline,vector3s,tmpLoopSpline.Length);
}
return(vector3s);
}
//andeeee from the Unity forum's steller Catmull-Rom class ( http://forum.unity3d.com/viewtopic.php?p=218400#218400 ):
private static Vector3 Interp(Vector3[] pts, float t){
int numSections = pts.Length - 3;
int currPt = Mathf.Min(Mathf.FloorToInt(t * (float) numSections), numSections - 1);
float u = t * (float) numSections - (float) currPt;
Vector3 a = pts[currPt];
Vector3 b = pts[currPt + 1];
Vector3 c = pts[currPt + 2];
Vector3 d = pts[currPt + 3];
return .5f * (
(-a + 3f * b - 3f * c + d) * (u * u * u)
+ (2f * a - 5f * b + 4f * c - d) * (u * u)
+ (-a + c) * u
+ 2f * b
);
}
//andeeee from the Unity forum's steller Catmull-Rom class ( http://forum.unity3d.com/viewtopic.php?p=218400#218400 ):
private class CRSpline {
public Vector3[] pts;
public CRSpline(params Vector3[] pts) {
this.pts = new Vector3[pts.Length];
Array.Copy(pts, this.pts, pts.Length);
}
public Vector3 Interp(float t) {
int numSections = pts.Length - 3;
int currPt = Mathf.Min(Mathf.FloorToInt(t * (float) numSections), numSections - 1);
float u = t * (float) numSections - (float) currPt;
Vector3 a = pts[currPt];
Vector3 b = pts[currPt + 1];
Vector3 c = pts[currPt + 2];
Vector3 d = pts[currPt + 3];
return .5f*((-a+3f*b-3f*c+d)*(u*u*u)+(2f*a-5f*b+4f*c-d)*(u*u)+(-a+c)*u+2f*b);
}
}
//catalog new tween and add component phase of iTween:
static void Launch(GameObject target, Hashtable args){
if(!args.Contains("id")){
args["id"] = GenerateID();
}
if(!args.Contains("target")){
args["target"] = target;
}
tweens.Insert(0,args);
target.AddComponent("iTween");
}
//cast any accidentally supplied doubles and ints as floats as iTween only uses floats internally and unify parameter case:
static Hashtable CleanArgs(Hashtable args){
Hashtable argsCopy = new Hashtable(args.Count);
Hashtable argsCaseUnified = new Hashtable(args.Count);
foreach (DictionaryEntry item in args) {
argsCopy.Add(item.Key, item.Value);
}
foreach (DictionaryEntry item in argsCopy) {
if(item.Value.GetType() == typeof(System.Int32)){
int original = (int)item.Value;
float casted = (float)original;
args[item.Key] = casted;
}
if(item.Value.GetType() == typeof(System.Double)){
double original = (double)item.Value;
float casted = (float)original;
args[item.Key] = casted;
}
}
//unify parameter case:
foreach (DictionaryEntry item in args) {
argsCaseUnified.Add(item.Key.ToString().ToLower(), item.Value);
}
//swap back case unification:
args = argsCaseUnified;
return args;
}
//random ID generator:
static string GenerateID(){
int strlen = 15;
char[] chars = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8'};
int num_chars = chars.Length - 1;
string randomChar = "";
for (int i = 0; i < strlen; i++) {
randomChar += chars[(int)Mathf.Floor(UnityEngine.Random.Range(0,num_chars))];
}
return randomChar;
}
//grab and set generic, neccesary iTween arguments:
void RetrieveArgs(){
foreach (Hashtable item in tweens) {
if((GameObject)item["target"] == gameObject){
tweenArguments=item;
break;
}
}
id=(string)tweenArguments["id"];
type=(string)tweenArguments["type"];
/* GFX47 MOD START */
_name=(string)tweenArguments["name"];
/* GFX47 MOD END */
method=(string)tweenArguments["method"];
if(tweenArguments.Contains("time")){
time=(float)tweenArguments["time"];
}else{
time=Defaults.time;
}
//do we need to use physics, is there a rigidbody?
if(rigidbody != null){
physics=true;
}
if(tweenArguments.Contains("delay")){
delay=(float)tweenArguments["delay"];
}else{
delay=Defaults.delay;
}
if(tweenArguments.Contains("namedcolorvalue")){
//allows namedcolorvalue to be set as either an enum(C# friendly) or a string(JS friendly), string case usage doesn't matter to further increase usability:
if(tweenArguments["namedcolorvalue"].GetType() == typeof(NamedValueColor)){
namedcolorvalue=(NamedValueColor)tweenArguments["namedcolorvalue"];
}else{
try {
namedcolorvalue=(NamedValueColor)Enum.Parse(typeof(NamedValueColor),(string)tweenArguments["namedcolorvalue"],true);
} catch {
Debug.LogWarning("iTween: Unsupported namedcolorvalue supplied! Default will be used.");
namedcolorvalue = iTween.NamedValueColor._Color;
}
}
}else{
namedcolorvalue=Defaults.namedColorValue;
}
if(tweenArguments.Contains("looptype")){
//allows loopType to be set as either an enum(C# friendly) or a string(JS friendly), string case usage doesn't matter to further increase usability:
if(tweenArguments["looptype"].GetType() == typeof(LoopType)){
loopType=(LoopType)tweenArguments["looptype"];
}else{
try {
loopType=(LoopType)Enum.Parse(typeof(LoopType),(string)tweenArguments["looptype"],true);
} catch {
Debug.LogWarning("iTween: Unsupported loopType supplied! Default will be used.");
loopType = iTween.LoopType.none;
}
}
}else{
loopType = iTween.LoopType.none;
}
if(tweenArguments.Contains("easetype")){
//allows easeType to be set as either an enum(C# friendly) or a string(JS friendly), string case usage doesn't matter to further increase usability:
if(tweenArguments["easetype"].GetType() == typeof(EaseType)){
easeType=(EaseType)tweenArguments["easetype"];
}else{
try {
easeType=(EaseType)Enum.Parse(typeof(EaseType),(string)tweenArguments["easetype"],true);
} catch {
Debug.LogWarning("iTween: Unsupported easeType supplied! Default will be used.");
easeType=Defaults.easeType;
}
}
}else{
easeType=Defaults.easeType;
}
if(tweenArguments.Contains("space")){
//allows space to be set as either an enum(C# friendly) or a string(JS friendly), string case usage doesn't matter to further increase usability:
if(tweenArguments["space"].GetType() == typeof(Space)){
space=(Space)tweenArguments["space"];
}else{
try {
space=(Space)Enum.Parse(typeof(Space),(string)tweenArguments["space"],true);
} catch {
Debug.LogWarning("iTween: Unsupported space supplied! Default will be used.");
space = Defaults.space;
}
}
}else{
space = Defaults.space;
}
if(tweenArguments.Contains("islocal")){
isLocal = (bool)tweenArguments["islocal"];
}else{
isLocal = Defaults.isLocal;
}
// Added by PressPlay
if (tweenArguments.Contains("ignoretimescale"))
{
useRealTime = (bool)tweenArguments["ignoretimescale"];
}
else
{
useRealTime = Defaults.useRealTime;
}
//instantiates a cached ease equation reference:
GetEasingFunction();
}
//instantiates a cached ease equation refrence:
void GetEasingFunction(){
switch (easeType){
case EaseType.easeInQuad:
ease = new EasingFunction(easeInQuad);
break;
case EaseType.easeOutQuad:
ease = new EasingFunction(easeOutQuad);
break;
case EaseType.easeInOutQuad:
ease = new EasingFunction(easeInOutQuad);
break;
case EaseType.easeInCubic:
ease = new EasingFunction(easeInCubic);
break;
case EaseType.easeOutCubic:
ease = new EasingFunction(easeOutCubic);
break;
case EaseType.easeInOutCubic:
ease = new EasingFunction(easeInOutCubic);
break;
case EaseType.easeInQuart:
ease = new EasingFunction(easeInQuart);
break;
case EaseType.easeOutQuart:
ease = new EasingFunction(easeOutQuart);
break;
case EaseType.easeInOutQuart:
ease = new EasingFunction(easeInOutQuart);
break;
case EaseType.easeInQuint:
ease = new EasingFunction(easeInQuint);
break;
case EaseType.easeOutQuint:
ease = new EasingFunction(easeOutQuint);
break;
case EaseType.easeInOutQuint:
ease = new EasingFunction(easeInOutQuint);
break;
case EaseType.easeInSine:
ease = new EasingFunction(easeInSine);
break;
case EaseType.easeOutSine:
ease = new EasingFunction(easeOutSine);
break;
case EaseType.easeInOutSine:
ease = new EasingFunction(easeInOutSine);
break;
case EaseType.easeInExpo:
ease = new EasingFunction(easeInExpo);
break;
case EaseType.easeOutExpo:
ease = new EasingFunction(easeOutExpo);
break;
case EaseType.easeInOutExpo:
ease = new EasingFunction(easeInOutExpo);
break;
case EaseType.easeInCirc:
ease = new EasingFunction(easeInCirc);
break;
case EaseType.easeOutCirc:
ease = new EasingFunction(easeOutCirc);
break;
case EaseType.easeInOutCirc:
ease = new EasingFunction(easeInOutCirc);
break;
case EaseType.linear:
ease = new EasingFunction(linear);
break;
case EaseType.spring:
ease = new EasingFunction(spring);
break;
/* GFX47 MOD START */
/*case EaseType.bounce:
ease = new EasingFunction(bounce);
break;*/
case EaseType.easeInBounce:
ease = new EasingFunction(easeInBounce);
break;
case EaseType.easeOutBounce:
ease = new EasingFunction(easeOutBounce);
break;
case EaseType.easeInOutBounce:
ease = new EasingFunction(easeInOutBounce);
break;
/* GFX47 MOD END */
case EaseType.easeInBack:
ease = new EasingFunction(easeInBack);
break;
case EaseType.easeOutBack:
ease = new EasingFunction(easeOutBack);
break;
case EaseType.easeInOutBack:
ease = new EasingFunction(easeInOutBack);
break;
/* GFX47 MOD START */
/*case EaseType.elastic:
ease = new EasingFunction(elastic);
break;*/
case EaseType.easeInElastic:
ease = new EasingFunction(easeInElastic);
break;
case EaseType.easeOutElastic:
ease = new EasingFunction(easeOutElastic);
break;
case EaseType.easeInOutElastic:
ease = new EasingFunction(easeInOutElastic);
break;
/* GFX47 MOD END */
}
}
//calculate percentage of tween based on time:
void UpdatePercentage(){
// Added by PressPlay
if (useRealTime)
{
runningTime += (Time.realtimeSinceStartup - lastRealTime);
}
else
{
runningTime += Time.deltaTime;
}
if(reverse){
percentage = 1 - runningTime/time;
}else{
percentage = runningTime/time;
}
lastRealTime = Time.realtimeSinceStartup; // Added by PressPlay
}
void CallBack(string callbackType){
if (tweenArguments.Contains(callbackType) && !tweenArguments.Contains("ischild")) {
//establish target:
GameObject target;
if (tweenArguments.Contains(callbackType+"target")) {
target=(GameObject)tweenArguments[callbackType+"target"];
}else{
target=gameObject;
}
//throw an error if a string wasn't passed for callback:
if (tweenArguments[callbackType].GetType() == typeof(System.String)) {
target.SendMessage((string)tweenArguments[callbackType],(object)tweenArguments[callbackType+"params"],SendMessageOptions.DontRequireReceiver);
}else{
Debug.LogError("iTween Error: Callback method references must be passed as a String!");
Destroy (this);
}
}
}
void Dispose(){
for (int i = 0; i < tweens.Count; i++) {
Hashtable tweenEntry = (Hashtable)tweens[i];
if ((string)tweenEntry["id"] == id){
tweens.RemoveAt(i);
break;
}
}
Destroy(this);
}
void ConflictCheck(){//if a new iTween is about to run and is of the same type as an in progress iTween this will destroy the previous if the new one is NOT identical in every way or it will destroy the new iTween if they are:
Component[] tweens = GetComponents(typeof(iTween));
foreach (iTween item in tweens) {
if(item.type == "value"){
return;
}else if(item.isRunning && item.type==type){
//cancel out if this is a shake or punch variant:
if (item.method != method) {
return;
}
//step 1: check for length first since it's the fastest:
if(item.tweenArguments.Count != tweenArguments.Count){
item.Dispose();
return;
}
//step 2: side-by-side check to figure out if this is an identical tween scenario to handle Update usages of iTween:
foreach (DictionaryEntry currentProp in tweenArguments) {
if(!item.tweenArguments.Contains(currentProp.Key)){
item.Dispose();
return;
}else{
if(!item.tweenArguments[currentProp.Key].Equals(tweenArguments[currentProp.Key]) && (string)currentProp.Key != "id"){//if we aren't comparing ids and something isn't exactly the same replace the running iTween:
item.Dispose();
return;
}
}
}
//step 3: prevent a new iTween addition if it is identical to the currently running iTween
Dispose();
//Destroy(this);
}
}
}
void EnableKinematic(){
/*
if(gameObject.GetComponent(typeof(Rigidbody))){
if(!rigidbody.isKinematic){
kinematic=true;
rigidbody.isKinematic=true;
}
}
*/
}
void DisableKinematic(){
/*
if(kinematic && rigidbody.isKinematic==true){
kinematic=false;
rigidbody.isKinematic=false;
}
*/
}
void ResumeDelay(){
StartCoroutine("TweenDelay");
}
#endregion
#region Easing Curves
private float linear(float start, float end, float value){
return Mathf.Lerp(start, end, value);
}
private float clerp(float start, float end, float value){
float min = 0.0f;
float max = 360.0f;
float half = Mathf.Abs((max - min) / 2.0f);
float retval = 0.0f;
float diff = 0.0f;
if ((end - start) < -half){
diff = ((max - start) + end) * value;
retval = start + diff;
}else if ((end - start) > half){
diff = -((max - end) + start) * value;
retval = start + diff;
}else retval = start + (end - start) * value;
return retval;
}
private float spring(float start, float end, float value){
value = Mathf.Clamp01(value);
value = (Mathf.Sin(value * Mathf.PI * (0.2f + 2.5f * value * value * value)) * Mathf.Pow(1f - value, 2.2f) + value) * (1f + (1.2f * (1f - value)));
return start + (end - start) * value;
}
private float easeInQuad(float start, float end, float value){
end -= start;
return end * value * value + start;
}
private float easeOutQuad(float start, float end, float value){
end -= start;
return -end * value * (value - 2) + start;
}
private float easeInOutQuad(float start, float end, float value){
value /= .5f;
end -= start;
if (value < 1) return end / 2 * value * value + start;
value--;
return -end / 2 * (value * (value - 2) - 1) + start;
}
private float easeInCubic(float start, float end, float value){
end -= start;
return end * value * value * value + start;
}
private float easeOutCubic(float start, float end, float value){
value--;
end -= start;
return end * (value * value * value + 1) + start;
}
private float easeInOutCubic(float start, float end, float value){
value /= .5f;
end -= start;
if (value < 1) return end / 2 * value * value * value + start;
value -= 2;
return end / 2 * (value * value * value + 2) + start;
}
private float easeInQuart(float start, float end, float value){
end -= start;
return end * value * value * value * value + start;
}
private float easeOutQuart(float start, float end, float value){
value--;
end -= start;
return -end * (value * value * value * value - 1) + start;
}
private float easeInOutQuart(float start, float end, float value){
value /= .5f;
end -= start;
if (value < 1) return end / 2 * value * value * value * value + start;
value -= 2;
return -end / 2 * (value * value * value * value - 2) + start;
}
private float easeInQuint(float start, float end, float value){
end -= start;
return end * value * value * value * value * value + start;
}
private float easeOutQuint(float start, float end, float value){
value--;
end -= start;
return end * (value * value * value * value * value + 1) + start;
}
private float easeInOutQuint(float start, float end, float value){
value /= .5f;
end -= start;
if (value < 1) return end / 2 * value * value * value * value * value + start;
value -= 2;
return end / 2 * (value * value * value * value * value + 2) + start;
}
private float easeInSine(float start, float end, float value){
end -= start;
return -end * Mathf.Cos(value / 1 * (Mathf.PI / 2)) + end + start;
}
private float easeOutSine(float start, float end, float value){
end -= start;
return end * Mathf.Sin(value / 1 * (Mathf.PI / 2)) + start;
}
private float easeInOutSine(float start, float end, float value){
end -= start;
return -end / 2 * (Mathf.Cos(Mathf.PI * value / 1) - 1) + start;
}
private float easeInExpo(float start, float end, float value){
end -= start;
return end * Mathf.Pow(2, 10 * (value / 1 - 1)) + start;
}
private float easeOutExpo(float start, float end, float value){
end -= start;
return end * (-Mathf.Pow(2, -10 * value / 1) + 1) + start;
}
private float easeInOutExpo(float start, float end, float value){
value /= .5f;
end -= start;
if (value < 1) return end / 2 * Mathf.Pow(2, 10 * (value - 1)) + start;
value--;
return end / 2 * (-Mathf.Pow(2, -10 * value) + 2) + start;
}
private float easeInCirc(float start, float end, float value){
end -= start;
return -end * (Mathf.Sqrt(1 - value * value) - 1) + start;
}
private float easeOutCirc(float start, float end, float value){
value--;
end -= start;
return end * Mathf.Sqrt(1 - value * value) + start;
}
private float easeInOutCirc(float start, float end, float value){
value /= .5f;
end -= start;
if (value < 1) return -end / 2 * (Mathf.Sqrt(1 - value * value) - 1) + start;
value -= 2;
return end / 2 * (Mathf.Sqrt(1 - value * value) + 1) + start;
}
/* GFX47 MOD START */
private float easeInBounce(float start, float end, float value){
end -= start;
float d = 1f;
return end - easeOutBounce(0, end, d-value) + start;
}
/* GFX47 MOD END */
/* GFX47 MOD START */
//private float bounce(float start, float end, float value){
private float easeOutBounce(float start, float end, float value){
value /= 1f;
end -= start;
if (value < (1 / 2.75f)){
return end * (7.5625f * value * value) + start;
}else if (value < (2 / 2.75f)){
value -= (1.5f / 2.75f);
return end * (7.5625f * (value) * value + .75f) + start;
}else if (value < (2.5 / 2.75)){
value -= (2.25f / 2.75f);
return end * (7.5625f * (value) * value + .9375f) + start;
}else{
value -= (2.625f / 2.75f);
return end * (7.5625f * (value) * value + .984375f) + start;
}
}
/* GFX47 MOD END */
/* GFX47 MOD START */
private float easeInOutBounce(float start, float end, float value){
end -= start;
float d = 1f;
if (value < d/2) return easeInBounce(0, end, value*2) * 0.5f + start;
else return easeOutBounce(0, end, value*2-d) * 0.5f + end*0.5f + start;
}
/* GFX47 MOD END */
private float easeInBack(float start, float end, float value){
end -= start;
value /= 1;
float s = 1.70158f;
return end * (value) * value * ((s + 1) * value - s) + start;
}
private float easeOutBack(float start, float end, float value){
float s = 1.70158f;
end -= start;
value = (value / 1) - 1;
return end * ((value) * value * ((s + 1) * value + s) + 1) + start;
}
private float easeInOutBack(float start, float end, float value){
float s = 1.70158f;
end -= start;
value /= .5f;
if ((value) < 1){
s *= (1.525f);
return end / 2 * (value * value * (((s) + 1) * value - s)) + start;
}
value -= 2;
s *= (1.525f);
return end / 2 * ((value) * value * (((s) + 1) * value + s) + 2) + start;
}
private float punch(float amplitude, float value){
float s = 9;
if (value == 0){
return 0;
}
if (value == 1){
return 0;
}
float period = 1 * 0.3f;
s = period / (2 * Mathf.PI) * Mathf.Asin(0);
return (amplitude * Mathf.Pow(2, -10 * value) * Mathf.Sin((value * 1 - s) * (2 * Mathf.PI) / period));
}
/* GFX47 MOD START */
private float easeInElastic(float start, float end, float value){
end -= start;
float d = 1f;
float p = d * .3f;
float s = 0;
float a = 0;
if (value == 0) return start;
if ((value /= d) == 1) return start + end;
if (a == 0f || a < Mathf.Abs(end)){
a = end;
s = p / 4;
}else{
s = p / (2 * Mathf.PI) * Mathf.Asin(end / a);
}
return -(a * Mathf.Pow(2, 10 * (value-=1)) * Mathf.Sin((value * d - s) * (2 * Mathf.PI) / p)) + start;
}
/* GFX47 MOD END */
/* GFX47 MOD START */
//private float elastic(float start, float end, float value){
private float easeOutElastic(float start, float end, float value){
/* GFX47 MOD END */
//Thank you to rafael.marteleto for fixing this as a port over from Pedro's UnityTween
end -= start;
float d = 1f;
float p = d * .3f;
float s = 0;
float a = 0;
if (value == 0) return start;
if ((value /= d) == 1) return start + end;
if (a == 0f || a < Mathf.Abs(end)){
a = end;
s = p / 4;
}else{
s = p / (2 * Mathf.PI) * Mathf.Asin(end / a);
}
return (a * Mathf.Pow(2, -10 * value) * Mathf.Sin((value * d - s) * (2 * Mathf.PI) / p) + end + start);
}
/* GFX47 MOD START */
private float easeInOutElastic(float start, float end, float value){
end -= start;
float d = 1f;
float p = d * .3f;
float s = 0;
float a = 0;
if (value == 0) return start;
if ((value /= d/2) == 2) return start + end;
if (a == 0f || a < Mathf.Abs(end)){
a = end;
s = p / 4;
}else{
s = p / (2 * Mathf.PI) * Mathf.Asin(end / a);
}
if (value < 1) return -0.5f * (a * Mathf.Pow(2, 10 * (value-=1)) * Mathf.Sin((value * d - s) * (2 * Mathf.PI) / p)) + start;
return a * Mathf.Pow(2, -10 * (value-=1)) * Mathf.Sin((value * d - s) * (2 * Mathf.PI) / p) * 0.5f + end + start;
}
/* GFX47 MOD END */
#endregion
#region Deprecated and Renamed
/*
public static void audioFrom(GameObject target, Hashtable args){Debug.LogError("iTween Error: audioFrom() has been renamed to AudioFrom().");}
public static void audioTo(GameObject target, Hashtable args){Debug.LogError("iTween Error: audioTo() has been renamed to AudioTo().");}
public static void colorFrom(GameObject target, Hashtable args){Debug.LogError("iTween Error: colorFrom() has been renamed to ColorFrom().");}
public static void colorTo(GameObject target, Hashtable args){Debug.LogError("iTween Error: colorTo() has been renamed to ColorTo().");}
public static void fadeFrom(GameObject target, Hashtable args){Debug.LogError("iTween Error: fadeFrom() has been renamed to FadeFrom().");}
public static void fadeTo(GameObject target, Hashtable args){Debug.LogError("iTween Error: fadeTo() has been renamed to FadeTo().");}
public static void lookFrom(GameObject target, Hashtable args){Debug.LogError("iTween Error: lookFrom() has been renamed to LookFrom().");}
public static void lookFromWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: lookFromWorld() has been deprecated. Please investigate LookFrom().");}
public static void lookTo(GameObject target, Hashtable args){Debug.LogError("iTween Error: lookTo() has been renamed to LookTo().");}
public static void lookToUpdate(GameObject target, Hashtable args){Debug.LogError("iTween Error: lookToUpdate() has been renamed to LookUpdate().");}
public static void lookToUpdateWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: lookToUpdateWorld() has been deprecated. Please investigate LookUpdate().");}
public static void moveAdd(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveAdd() has been renamed to MoveAdd().");}
public static void moveAddWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveAddWorld() has been deprecated. Please investigate MoveAdd().");}
public static void moveBy(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveBy() has been renamed to MoveBy().");}
public static void moveByWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveAddWorld() has been deprecated. Please investigate MoveAdd().");}
public static void moveFrom(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveFrom() has been renamed to MoveFrom().");}
public static void moveFromWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveFromWorld() has been deprecated. Please investigate MoveFrom().");}
public static void moveTo(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveTo() has been renamed to MoveTo().");}
public static void moveToBezier(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveToBezier() has been deprecated. Please investigate MoveTo() and the "path" property.");}
public static void moveToBezierWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveToBezierWorld() has been deprecated. Please investigate MoveTo() and the "path" property.");}
public static void moveToUpdate(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveToUpdate() has been renamed to MoveUpdate().");}
public static void moveToUpdateWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveToUpdateWorld() has been deprecated. Please investigate MoveUpdate().");}
public static void moveToWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: moveToWorld() has been deprecated. Please investigate MoveTo().");}
public static void punchPosition(GameObject target, Hashtable args){Debug.LogError("iTween Error: punchPosition() has been renamed to PunchPosition().");}
public static void punchPositionWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: punchPositionWorld() has been deprecated. Please investigate PunchPosition().");}
public static void punchRotation(GameObject target, Hashtable args){Debug.LogError("iTween Error: punchPosition() has been renamed to PunchRotation().");}
public static void punchRotationWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: punchRotationWorld() has been deprecated. Please investigate PunchRotation().");}
public static void punchScale(GameObject target, Hashtable args){Debug.LogError("iTween Error: punchScale() has been renamed to PunchScale().");}
public static void rotateAdd(GameObject target, Hashtable args){Debug.LogError("iTween Error: rotateAdd() has been renamed to RotateAdd().");}
public static void rotateBy(GameObject target, Hashtable args){Debug.LogError("iTween Error: rotateBy() has been renamed to RotateBy().");}
public static void rotateByWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: rotateByWorld() has been deprecated. Please investigate RotateBy().");}
public static void rotateFrom(GameObject target, Hashtable args){Debug.LogError("iTween Error: rotateFrom() has been renamed to RotateFrom().");}
public static void rotateTo(GameObject target, Hashtable args){Debug.LogError("iTween Error: rotateTo() has been renamed to RotateTo().");}
public static void scaleAdd(GameObject target, Hashtable args){Debug.LogError("iTween Error: scaleAdd() has been renamed to ScaleAdd().");}
public static void scaleBy(GameObject target, Hashtable args){Debug.LogError("iTween Error: scaleBy() has been renamed to ScaleBy().");}
public static void scaleFrom(GameObject target, Hashtable args){Debug.LogError("iTween Error: scaleFrom() has been renamed to ScaleFrom().");}
public static void scaleTo(GameObject target, Hashtable args){Debug.LogError("iTween Error: scaleTo() has been renamed to ScaleTo().");}
public static void shake(GameObject target, Hashtable args){Debug.LogError("iTween Error: scale() has been deprecated. Please investigate ShakePosition(), ShakeRotation() and ShakeScale().");}
public static void shakeWorld(GameObject target, Hashtable args){Debug.LogError("iTween Error: shakeWorld() has been deprecated. Please investigate ShakePosition(), ShakeRotation() and ShakeScale().");}
public static void stab(GameObject target, Hashtable args){Debug.LogError("iTween Error: stab() has been renamed to Stab().");}
public static void stop(GameObject target, Hashtable args){Debug.LogError("iTween Error: stop() has been renamed to Stop().");}
public static void stopType(GameObject target, Hashtable args){Debug.LogError("iTween Error: stopType() has been deprecated. Please investigate Stop().");}
public static void tweenCount(GameObject target, Hashtable args){Debug.LogError("iTween Error: tweenCount() has been deprecated. Please investigate Count().");}
*/
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/iTweenEditor/iTween.cs
|
C#
|
asf20
| 272,069
|
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
public class StartAndStopTween : MonoBehaviour {
public GameObject target;
void OnGUI() {
// if(GUILayout.Button("Start Bounce")) {
// iTweenEvent.GetEvent(target, "Bounce").Play();
// }
//
// if(GUILayout.Button("Stop Bounce")) {
// iTweenEvent.GetEvent(target, "Bounce").Stop();
// }
//
// if(GUILayout.Button("Start Color Fade")) {
// iTweenEvent.GetEvent(target, "Color Fade").Play();
// }
//
// if(GUILayout.Button("Stop Color Fade")) {
// iTweenEvent.GetEvent(target, "Color Fade").Stop();
// }
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/iTweenEditor/Examples/StartAndStopTween.cs
|
C#
|
asf20
| 647
|
// Copyright (c) 2009-2012 David Koontz
// Please direct any bugs/comments/suggestions to david@koontzfamily.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[System.Serializable]
public class ArrayIndexes
{
public int[] indexes;
}
public class iTweenEvent : MonoBehaviour
{
public const string VERSION = "0.6.1";
public enum TweenType
{
AudioFrom,
AudioTo,
AudioUpdate,
CameraFadeFrom,
CameraFadeTo,
ColorFrom,
ColorTo,
ColorUpdate,
FadeFrom,
FadeTo,
FadeUpdate,
LookFrom,
LookTo,
LookUpdate,
MoveAdd,
MoveBy,
MoveFrom,
MoveTo,
MoveToXY,
MoveUpdate,
PunchPosition,
PunchRotation,
PunchScale,
RotateAdd,
RotateBy,
RotateFrom,
RotateTo,
RotateUpdate,
ScaleAdd,
ScaleBy,
ScaleFrom,
ScaleTo,
ScaleUpdate,
ShakePosition,
ShakeRotation,
ShakeScale,
Stab,
ValueTo
}
public string tweenName = "";
public bool playAutomatically = false;
public float delay = 0;
public iTweenEvent.TweenType type = iTweenEvent.TweenType.MoveTo;
public bool showIconInInspector = false;
/// <summary>
/// Finds an iTweenEvent on a GameObject
/// </summary>
/// <param name="obj">
/// The <see cref="GameObject"/> to look under
/// </param>
/// <param name="name">
/// The name of the <see cref="iTweenEvent"/> to look for
/// </param>
/// <returns>
/// A <see cref="iTweenEvent"/>
/// </returns>
public static iTweenEvent GetEvent(GameObject obj, string name)
{
var tweens = obj.GetComponents<iTweenEvent>();
if (tweens.Length > 0)
{
var result = tweens.FirstOrDefault(tween => { return tween.tweenName == name; });
if (result != null)
{
return result;
}
}
throw new System.ArgumentException("No tween with the name '" + name + "' could be found on the GameObject named '" + obj.name + "'");
}
public Dictionary<string, object> Values
{
get
{
if (null == values)
{
DeserializeValues();
}
return values;
}
set
{
values = value;
SerializeValues();
}
}
[SerializeField]
string[] keys;
[SerializeField]
int[] indexes;
[SerializeField]
string[] metadatas;
[SerializeField]
int[] ints;
[SerializeField]
float[] floats;
[SerializeField]
bool[] bools;
[SerializeField]
string[] strings;
[SerializeField]
Vector3[] vector3s;
[SerializeField]
Color[] colors;
[SerializeField]
Space[] spaces;
[SerializeField]
iTween.EaseType[] easeTypes;
[SerializeField]
iTween.LoopType[] loopTypes;
[SerializeField]
GameObject[] gameObjects;
[SerializeField]
Transform[] transforms;
[SerializeField]
AudioClip[] audioClips;
[SerializeField]
AudioSource[] audioSources;
[SerializeField]
ArrayIndexes[] vector3Arrays;
[SerializeField]
ArrayIndexes[] transformArrays;
[SerializeField]
iTweenPath[] paths;
Dictionary<string, object> values;
public void Start()
{
if (playAutomatically)
{
Play();
}
}
public void Play()
{
StartCoroutine(StartEvent());
}
public void OnDrawGizmos()
{
if (showIconInInspector)
{
//Gizmos.DrawIcon(transform.position, "iTweenIcon.tif");
}
}
private GameObject target = null;
public void SetObjectTarget(GameObject _target)
{
target = _target;
}
public GameObject GetGameObject()
{
if (target != null)
return target;
else
return gameObject;
}
IEnumerator StartEvent()
{
if (delay > 0) yield return new WaitForSeconds(delay);
var optionsHash = new Hashtable();
foreach (var pair in Values)
{
if ("path" == pair.Key && pair.Value.GetType() == typeof(string))
{
optionsHash.Add(pair.Key, iTweenPath.GetPath((string)pair.Value));
}
else
{
optionsHash.Add(pair.Key, pair.Value);
}
}
switch (type)
{
case TweenType.AudioFrom:
iTween.AudioFrom(GetGameObject(), optionsHash);
break;
case TweenType.AudioTo:
iTween.AudioTo(GetGameObject(), optionsHash);
break;
case TweenType.AudioUpdate:
iTween.AudioUpdate(GetGameObject(), optionsHash);
break;
case TweenType.CameraFadeFrom:
iTween.CameraFadeFrom(optionsHash);
break;
case TweenType.CameraFadeTo:
iTween.CameraFadeTo(optionsHash);
break;
case TweenType.ColorFrom:
iTween.ColorFrom(GetGameObject(), optionsHash);
break;
case TweenType.ColorTo:
iTween.ColorTo(GetGameObject(), optionsHash);
break;
case TweenType.ColorUpdate:
iTween.ColorUpdate(GetGameObject(), optionsHash);
break;
case TweenType.FadeFrom:
iTween.FadeFrom(GetGameObject(), optionsHash);
break;
case TweenType.FadeTo:
iTween.FadeTo(GetGameObject(), optionsHash);
break;
case TweenType.FadeUpdate:
iTween.FadeUpdate(GetGameObject(), optionsHash);
break;
case TweenType.LookFrom:
iTween.LookFrom(GetGameObject(), optionsHash);
break;
case TweenType.LookTo:
iTween.LookTo(GetGameObject(), optionsHash);
break;
case TweenType.LookUpdate:
iTween.LookUpdate(GetGameObject(), optionsHash);
break;
case TweenType.MoveAdd:
iTween.MoveAdd(GetGameObject(), optionsHash);
break;
case TweenType.MoveBy:
iTween.MoveBy(GetGameObject(), optionsHash);
break;
case TweenType.MoveFrom:
iTween.MoveFrom(GetGameObject(), optionsHash);
break;
case TweenType.MoveTo:
iTween.MoveTo(GetGameObject(), optionsHash);
break;
case TweenType.MoveToXY:
{
if (optionsHash.ContainsKey("positionXY"))
{
Vector3 vec = (Vector3)optionsHash["positionXY"];
Vector3 vec3 = new Vector3(vec.x, vec.y, GetGameObject().transform.localPosition.z);
optionsHash["position"] = vec3;
optionsHash["islocal"] = true;
}
iTween.MoveTo(GetGameObject(), optionsHash);
}
break;
case TweenType.MoveUpdate:
iTween.MoveUpdate(GetGameObject(), optionsHash);
break;
case TweenType.PunchPosition:
iTween.PunchPosition(GetGameObject(), optionsHash);
break;
case TweenType.PunchRotation:
iTween.PunchRotation(GetGameObject(), optionsHash);
break;
case TweenType.PunchScale:
iTween.PunchScale(GetGameObject(), optionsHash);
break;
case TweenType.RotateAdd:
iTween.RotateAdd(GetGameObject(), optionsHash);
break;
case TweenType.RotateBy:
iTween.RotateBy(GetGameObject(), optionsHash);
break;
case TweenType.RotateFrom:
iTween.RotateFrom(GetGameObject(), optionsHash);
break;
case TweenType.RotateTo:
iTween.RotateTo(GetGameObject(), optionsHash);
break;
case TweenType.RotateUpdate:
iTween.RotateUpdate(GetGameObject(), optionsHash);
break;
case TweenType.ScaleAdd:
iTween.ScaleAdd(GetGameObject(), optionsHash);
break;
case TweenType.ScaleBy:
iTween.ScaleBy(GetGameObject(), optionsHash);
break;
case TweenType.ScaleFrom:
iTween.ScaleFrom(GetGameObject(), optionsHash);
break;
case TweenType.ScaleTo:
iTween.ScaleTo(GetGameObject(), optionsHash);
break;
case TweenType.ScaleUpdate:
iTween.ScaleUpdate(GetGameObject(), optionsHash);
break;
case TweenType.ShakePosition:
iTween.ShakePosition(GetGameObject(), optionsHash);
break;
case TweenType.ShakeRotation:
iTween.ShakeRotation(GetGameObject(), optionsHash);
break;
case TweenType.ShakeScale:
iTween.ShakeScale(GetGameObject(), optionsHash);
break;
case TweenType.Stab:
iTween.Stab(GetGameObject(), optionsHash);
break;
case TweenType.ValueTo:
optionsHash["onupdate"] = "OnUpdateAlpha";
optionsHash["oncomplete"] = "OnResetAlpha";
iTween.ValueTo(GetGameObject(), optionsHash);
break;
default:
throw new System.ArgumentException("Invalid tween type: " + type);
}
}
public void OnChangeAlpha(double num)
{
Debug.LogError("OnChangeAlpha");
}
void SerializeValues()
{
var keyList = new List<string>();
var indexList = new List<int>();
var metadataList = new List<string>();
var intList = new List<int>();
var floatList = new List<float>();
var boolList = new List<bool>();
var stringList = new List<string>();
var vector3List = new List<Vector3>();
var colorList = new List<Color>();
var spaceList = new List<Space>();
var easeTypeList = new List<iTween.EaseType>();
var loopTypeList = new List<iTween.LoopType>();
var gameObjectList = new List<GameObject>();
var transformList = new List<Transform>();
var audioClipList = new List<AudioClip>();
var audioSourceList = new List<AudioSource>();
var vector3ArrayList = new List<ArrayIndexes>();
var transformArrayList = new List<ArrayIndexes>();
foreach (var pair in values)
{
var mappings = EventParamMappings.mappings[type];
var valueType = mappings[pair.Key];
if (typeof(int) == valueType)
{
AddToList<int>(keyList, indexList, intList, metadataList, pair);
}
if (typeof(float) == valueType)
{
AddToList<float>(keyList, indexList, floatList, metadataList, pair);
}
else if (typeof(bool) == valueType)
{
AddToList<bool>(keyList, indexList, boolList, metadataList, pair);
}
else if (typeof(string) == valueType)
{
AddToList<string>(keyList, indexList, stringList, metadataList, pair);
}
else if (typeof(Vector3) == valueType)
{
AddToList<Vector3>(keyList, indexList, vector3List, metadataList, pair);
}
else if (typeof(Color) == valueType)
{
AddToList<Color>(keyList, indexList, colorList, metadataList, pair);
}
else if (typeof(Space) == valueType)
{
AddToList<Space>(keyList, indexList, spaceList, metadataList, pair);
}
else if (typeof(iTween.EaseType) == valueType)
{
AddToList<iTween.EaseType>(keyList, indexList, easeTypeList, metadataList, pair);
}
else if (typeof(iTween.LoopType) == valueType)
{
AddToList<iTween.LoopType>(keyList, indexList, loopTypeList, metadataList, pair);
}
else if (typeof(GameObject) == valueType)
{
AddToList<GameObject>(keyList, indexList, gameObjectList, metadataList, pair);
}
else if (typeof(Transform) == valueType)
{
AddToList<Transform>(keyList, indexList, transformList, metadataList, pair);
}
else if (typeof(AudioClip) == valueType)
{
AddToList<AudioClip>(keyList, indexList, audioClipList, metadataList, pair);
}
else if (typeof(AudioSource) == valueType)
{
AddToList<AudioSource>(keyList, indexList, audioSourceList, metadataList, pair);
}
else if (typeof(Vector3OrTransform) == valueType)
{
if (pair.Value == null || typeof(Transform) == pair.Value.GetType())
{
AddToList<Transform>(keyList, indexList, transformList, metadataList, pair.Key, pair.Value, "t");
}
else
{
AddToList<Vector3>(keyList, indexList, vector3List, metadataList, pair.Key, pair.Value, "v");
}
}
else if (typeof(Vector3OrTransformArray) == valueType)
{
if (typeof(Vector3[]) == pair.Value.GetType())
{
var value = (Vector3[])pair.Value;
var vectorIndexes = new ArrayIndexes();
var indexArray = new int[value.Length];
for (var i = 0; i < value.Length; ++i)
{
vector3List.Add((Vector3)value[i]);
indexArray[i] = vector3List.Count - 1;
}
vectorIndexes.indexes = indexArray;
AddToList<ArrayIndexes>(keyList, indexList, vector3ArrayList, metadataList, pair.Key, vectorIndexes, "v");
}
else if (typeof(Transform[]) == pair.Value.GetType())
{
var value = (Transform[])pair.Value;
var transformIndexes = new ArrayIndexes();
var indexArray = new int[value.Length];
for (var i = 0; i < value.Length; ++i)
{
transformList.Add((Transform)value[i]);
indexArray[i] = transformList.Count - 1;
}
transformIndexes.indexes = indexArray;
AddToList<ArrayIndexes>(keyList, indexList, transformArrayList, metadataList, pair.Key, transformIndexes, "t");
}
else if (typeof(string) == pair.Value.GetType())
{
AddToList<string>(keyList, indexList, stringList, metadataList, pair.Key, pair.Value, "p");
}
}
}
keys = keyList.ToArray();
indexes = indexList.ToArray();
metadatas = metadataList.ToArray();
ints = intList.ToArray();
floats = floatList.ToArray();
bools = boolList.ToArray();
strings = stringList.ToArray();
vector3s = vector3List.ToArray();
colors = colorList.ToArray();
spaces = spaceList.ToArray();
easeTypes = easeTypeList.ToArray();
loopTypes = loopTypeList.ToArray();
gameObjects = gameObjectList.ToArray();
transforms = transformList.ToArray();
audioClips = audioClipList.ToArray();
audioSources = audioSourceList.ToArray();
vector3Arrays = vector3ArrayList.ToArray();
transformArrays = transformArrayList.ToArray();
}
void AddToList<T>(List<string> keyList, List<int> indexList, IList<T> valueList, List<string> metadataList, KeyValuePair<string, object> pair)
{
AddToList<T>(keyList, indexList, valueList, metadataList, pair.Key, pair.Value);
}
void AddToList<T>(List<string> keyList, List<int> indexList, IList<T> valueList, List<string> metadataList, KeyValuePair<string, object> pair, string metadata)
{
AddToList<T>(keyList, indexList, valueList, metadataList, pair.Key, pair.Value, metadata);
}
void AddToList<T>(List<string> keyList, List<int> indexList, IList<T> valueList, List<string> metadataList, string key, object value)
{
AddToList<T>(keyList, indexList, valueList, metadataList, key, value, null);
}
void AddToList<T>(List<string> keyList, List<int> indexList, IList<T> valueList, List<string> metadataList, string key, object value, string metadata)
{
keyList.Add(key);
valueList.Add((T)value);
indexList.Add(valueList.Count - 1);
metadataList.Add(metadata);
}
void DeserializeValues()
{
values = new Dictionary<string, object>();
if (null == keys)
{
return;
}
for (var i = 0; i < keys.Length; ++i)
{
var mappings = EventParamMappings.mappings[type];
var valueType = mappings[keys[i]];
if (typeof(int) == valueType)
{
values.Add(keys[i], ints[indexes[i]]);
}
else if (typeof(float) == valueType)
{
values.Add(keys[i], floats[indexes[i]]);
}
else if (typeof(bool) == valueType)
{
values.Add(keys[i], bools[indexes[i]]);
}
else if (typeof(string) == valueType)
{
values.Add(keys[i], strings[indexes[i]]);
}
else if (typeof(Vector3) == valueType)
{
values.Add(keys[i], vector3s[indexes[i]]);
}
else if (typeof(Color) == valueType)
{
values.Add(keys[i], colors[indexes[i]]);
}
else if (typeof(Space) == valueType)
{
values.Add(keys[i], spaces[indexes[i]]);
}
else if (typeof(iTween.EaseType) == valueType)
{
values.Add(keys[i], easeTypes[indexes[i]]);
}
else if (typeof(iTween.LoopType) == valueType)
{
values.Add(keys[i], loopTypes[indexes[i]]);
}
else if (typeof(GameObject) == valueType)
{
values.Add(keys[i], gameObjects[indexes[i]]);
}
else if (typeof(Transform) == valueType)
{
values.Add(keys[i], transforms[indexes[i]]);
}
else if (typeof(AudioClip) == valueType)
{
values.Add(keys[i], audioClips[indexes[i]]);
}
else if (typeof(AudioSource) == valueType)
{
values.Add(keys[i], audioSources[indexes[i]]);
}
else if (typeof(Vector3OrTransform) == valueType)
{
if ("v" == metadatas[i])
{
values.Add(keys[i], vector3s[indexes[i]]);
}
else if ("t" == metadatas[i])
{
values.Add(keys[i], transforms[indexes[i]]);
}
}
else if (typeof(Vector3OrTransformArray) == valueType)
{
if ("v" == metadatas[i])
{
var arrayIndexes = vector3Arrays[indexes[i]];
var vectorArray = new Vector3[arrayIndexes.indexes.Length];
for (var idx = 0; idx < arrayIndexes.indexes.Length; ++idx)
{
vectorArray[idx] = vector3s[arrayIndexes.indexes[idx]];
}
values.Add(keys[i], vectorArray);
}
else if ("t" == metadatas[i])
{
var arrayIndexes = transformArrays[indexes[i]];
var transformArray = new Transform[arrayIndexes.indexes.Length];
for (var idx = 0; idx < arrayIndexes.indexes.Length; ++idx)
{
transformArray[idx] = transforms[arrayIndexes.indexes[idx]];
}
values.Add(keys[i], transformArray);
}
else if ("p" == metadatas[i])
{
values.Add(keys[i], strings[indexes[i]]);
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/iTweenEditor/iTweenEvent.cs
|
C#
|
asf20
| 22,904
|
//by Bob Berkebile : Pixelplacement : http://www.pixelplacement.com
using UnityEngine;
using System.Collections.Generic;
public class iTweenPath : MonoBehaviour
{
public string pathName ="";
public Color pathColor = Color.cyan;
public List<Vector3> nodes = new List<Vector3>(){Vector3.zero, Vector3.zero};
public int nodeCount;
public static Dictionary<string, iTweenPath> paths = new Dictionary<string, iTweenPath>();
public bool initialized = false;
public string initialName = "";
void OnEnable(){
paths.Add(pathName.ToLower(), this);
}
void OnDrawGizmosSelected(){
if(enabled) { // dkoontz
if(nodes.Count > 0){
iTween.DrawPath(nodes.ToArray(), pathColor);
}
} // dkoontz
}
public static Vector3[] GetPath(string requestedName){
requestedName = requestedName.ToLower();
if(paths.ContainsKey(requestedName)){
return paths[requestedName].nodes.ToArray();
}else{
Debug.Log("No path with that name exists! Are you sure you wrote it correctly?");
return null;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/iTweenEditor/iTweenPath.cs
|
C#
|
asf20
| 1,019
|
using UnityEngine;
using System.Collections;
public class AnimateSwapTextures : MonoBehaviour
{
public Texture2D[] textures;
public string textureName;
public int fps;
private int currentFrame;
private float currentFrameTime;
// Cache
public Material material;
void Awake()
{
if (string.IsNullOrEmpty(textureName))
textureName = "_MainTex";
if( material == null )
material = renderer.sharedMaterial;
}
void Start()
{
material.mainTexture = textures[currentFrame];
}
// Update is called once per frame
void Update () {
currentFrameTime += Time.deltaTime;
if (currentFrameTime >= (1f / fps))
{
AdvanceFrame();
material.SetTexture(textureName, textures[currentFrame]);
currentFrameTime = 0;
}
}
void AdvanceFrame()
{
currentFrame++;
if (currentFrame >= textures.Length)
currentFrame = 0;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Behaviours/AnimateSwapTextures.cs
|
C#
|
asf20
| 895
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Using Find and Replace for every script file in the project ( ": GMonoBehaviour" -> ": GMonoBehaviour"
/// </summary>
public class GMonoBehaviour : /*Exclude from find and replace*/MonoBehaviour
{
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Behaviours/GMonoBehaviour.cs
|
C#
|
asf20
| 275
|
using UnityEngine;
using System.Collections;
[AddComponentMenu("Utilities/HUDFPS")]
public class HUDFPS : MonoBehaviour
{
// Attach this to any object to make a frames/second indicator.
//
// It calculates frames/second over each updateInterval,
// so the display does not keep changing wildly.
//
// It is also fairly accurate at very low FPS counts (<10).
// We do this not by simply counting frames per interval, but
// by accumulating FPS for each frame. This way we end up with
// corstartRect overall FPS even if the interval renders something like
// 5.5 frames.
public bool render = false;
public Rect startRect = new Rect(80, 40, 75, 50); // The rect the window is initially displayed at.
public bool updateColor = true; // Do you want the color to change if the FPS gets low
public bool allowDrag = true; // Do you want to allow the dragging of the FPS window
public float frequency = 0.5F; // The update frequency of the fps
public int nbDecimal = 1; // How many decimal do you want to display
private float accum = 0f; // FPS accumulated over the interval
private int frames = 0; // Frames drawn over the interval
private Color color = Color.white; // The color of the GUI, depending of the FPS ( R < 10, Y < 30, G >= 30 )
private string sFPS = ""; // The fps formatted into a string.
private GUIStyle style; // The style the text will be displayed at, based en defaultSkin.label.
void Start()
{
StartCoroutine(FPS());
}
void Update()
{
accum += Time.timeScale / Time.deltaTime;
++frames;
}
IEnumerator FPS()
{
// Infinite loop executed every "frenquency" secondes.
while (true)
{
// Update the FPS
float fps = accum / frames;
sFPS = fps.ToString("f" + Mathf.Clamp(nbDecimal, 0, 10));
//Update the color
color = (fps >= 30) ? Color.green : ((fps > 10) ? Color.red : Color.yellow);
accum = 0.0F;
frames = 0;
yield return new WaitForSeconds(frequency);
}
}
void OnGUI()
{
if (!render)
return;
// Copy the default label skin, change the color and the alignement
if (style == null)
{
style = new GUIStyle(GUI.skin.label);
style.normal.textColor = Color.white;
style.alignment = TextAnchor.MiddleCenter;
}
GUI.color = updateColor ? color : Color.white;
startRect = GUI.Window(0, startRect, DoMyWindow, "");
}
void DoMyWindow(int windowID)
{
GUI.Label(new Rect(0, 0, startRect.width, startRect.height), sFPS + " FPS\n" , style);
if (allowDrag) GUI.DragWindow(new Rect(0, 0, Screen.width, Screen.height));
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Behaviours/HUDFPS.cs
|
C#
|
asf20
| 2,653
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("GFramework/Global Data")]
public class GlobalData : GMonoBehaviour
{
private static Dictionary<string, GameObject> cache = new Dictionary<string, GameObject>();
// Use this for initialization
void Awake()
{
DontDestroyOnLoad(gameObject);
if (cache.ContainsKey(name))
{
Debug.LogWarning("Object [" + name + "] exists. Destroy new one");
Object.DestroyImmediate(this.gameObject);
}
else
cache[name] = gameObject;
}
void Start()
{
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Behaviours/GlobalData.cs
|
C#
|
asf20
| 595
|
using UnityEngine;
using System.Collections;
public class TimedTrailRenderer : MonoBehaviour
{
public bool emit = true;
public float emitTime = 0.00f;
public Material material;
public float lifeTime = 1.00f;
public Color[] colors;
public float[] sizes;
public float uvLengthScale = 0.01f;
public bool higherQualityUVs = true;
public int movePixelsForRebuild = 6;
public float maxRebuildTime = 0.1f;
public float minVertexDistance = 0.10f;
public float maxVertexDistance = 10.00f;
public float maxAngle = 3.00f;
public bool autoDestruct = false;
private ArrayList points = new ArrayList();
private GameObject o;
private Vector3 lastPosition;
private Vector3 lastCameraPosition1;
private Vector3 lastCameraPosition2;
private float lastRebuildTime = 0.00f;
private bool lastFrameEmit = true;
public class Point
{
public float timeCreated = 0.00f;
public Vector3 position;
public bool lineBreak = false;
}
void Start()
{
lastPosition = transform.position;
o = new GameObject("Trail");
o.transform.parent = null;
o.transform.position = Vector3.zero;
o.transform.rotation = Quaternion.identity;
o.transform.localScale = Vector3.one;
o.AddComponent(typeof(MeshFilter));
o.AddComponent(typeof(MeshRenderer));
o.renderer.material = material;
}
void OnEnable()
{
lastPosition = transform.position;
o = new GameObject("Trail");
o.transform.parent = null;
o.transform.position = Vector3.zero;
o.transform.rotation = Quaternion.identity;
o.transform.localScale = Vector3.one;
o.AddComponent(typeof(MeshFilter));
o.AddComponent(typeof(MeshRenderer));
o.renderer.material = material;
}
void OnDisable()
{
Destroy(o);
}
void Update()
{
if (emit && emitTime != 0)
{
emitTime -= Time.deltaTime;
if (emitTime == 0) emitTime = -1;
if (emitTime < 0) emit = false;
}
if (!emit && points.Count == 0 && autoDestruct)
{
Destroy(o);
Destroy(gameObject);
}
// early out if there is no camera
if (!Camera.main) return;
bool re = false;
// if we have moved enough, create a new vertex and make sure we rebuild the mesh
float theDistance = (lastPosition - transform.position).magnitude;
if (emit)
{
if (theDistance > minVertexDistance)
{
bool make = false;
if (points.Count < 3)
{
make = true;
}
else
{
Vector3 l1 = ((Point)points[points.Count - 2]).position - ((Point)points[points.Count - 3]).position;
Vector3 l2 = ((Point)points[points.Count - 1]).position - ((Point)points[points.Count - 2]).position;
if (Vector3.Angle(l1, l2) > maxAngle || theDistance > maxVertexDistance) make = true;
}
if (make)
{
Point p = new Point();
p.position = transform.position;
p.timeCreated = Time.time;
points.Add(p);
lastPosition = transform.position;
}
else
{
((Point)points[points.Count - 1]).position = transform.position;
((Point)points[points.Count - 1]).timeCreated = Time.time;
}
}
else if (points.Count > 0)
{
((Point)points[points.Count - 1]).position = transform.position;
((Point)points[points.Count - 1]).timeCreated = Time.time;
}
}
if (!emit && lastFrameEmit && points.Count > 0) ((Point)points[points.Count - 1]).lineBreak = true;
lastFrameEmit = emit;
// approximate if we should rebuild the mesh or not
if (points.Count > 1)
{
Vector3 cur1 = Camera.main.WorldToScreenPoint(((Point)points[0]).position);
lastCameraPosition1.z = 0;
Vector3 cur2 = Camera.main.WorldToScreenPoint(((Point)points[points.Count - 1]).position);
lastCameraPosition2.z = 0;
float distance = (lastCameraPosition1 - cur1).magnitude;
distance += (lastCameraPosition2 - cur2).magnitude;
if (distance > movePixelsForRebuild || Time.time - lastRebuildTime > maxRebuildTime)
{
re = true;
lastCameraPosition1 = cur1;
lastCameraPosition2 = cur2;
}
}
else
{
re = true;
}
if (re)
{
lastRebuildTime = Time.time;
ArrayList remove = new ArrayList();
int i = 0;
foreach (Point p in points)
{
// cull old points first
if (Time.time - p.timeCreated > lifeTime) remove.Add(p);
i++;
}
foreach (Point p in remove) points.Remove(p);
remove.Clear();
if (points.Count > 1)
{
Vector3[] newVertices = new Vector3[points.Count * 2];
Vector2[] newUV = new Vector2[points.Count * 2];
int[] newTriangles = new int[(points.Count - 1) * 6];
Color[] newColors = new Color[points.Count * 2];
i = 0;
float curDistance = 0.00f;
foreach (Point p in points)
{
float time = (Time.time - p.timeCreated) / lifeTime;
Color color = Color.Lerp(Color.white, Color.clear, time);
if (colors != null && colors.Length > 0)
{
float colorTime = time * (colors.Length - 1);
float min = Mathf.Floor(colorTime);
float max = Mathf.Clamp(Mathf.Ceil(colorTime), 1, colors.Length - 1);
float lerp = Mathf.InverseLerp(min, max, colorTime);
if (min >= colors.Length) min = colors.Length - 1; if (min < 0) min = 0;
if (max >= colors.Length) max = colors.Length - 1; if (max < 0) max = 0;
color = Color.Lerp(colors[(int)min], colors[(int)max], lerp);
}
float size = 1f;
if (sizes != null && sizes.Length > 0)
{
float sizeTime = time * (sizes.Length - 1);
float min = Mathf.Floor(sizeTime);
float max = Mathf.Clamp(Mathf.Ceil(sizeTime), 1, sizes.Length - 1);
float lerp = Mathf.InverseLerp(min, max, sizeTime);
if (min >= sizes.Length) min = sizes.Length - 1; if (min < 0) min = 0;
if (max >= sizes.Length) max = sizes.Length - 1; if (max < 0) max = 0;
size = Mathf.Lerp(sizes[(int)min], sizes[(int)max], lerp);
}
Vector3 lineDirection = Vector3.zero;
if (i == 0) lineDirection = p.position - ((Point)points[i + 1]).position;
else lineDirection = ((Point)points[i - 1]).position - p.position;
Vector3 vectorToCamera = Camera.main.transform.position - p.position;
Vector3 perpendicular = Vector3.Cross(lineDirection, vectorToCamera).normalized;
newVertices[i * 2] = p.position + (perpendicular * (size * 0.5f));
newVertices[(i * 2) + 1] = p.position + (-perpendicular * (size * 0.5f));
newColors[i * 2] = newColors[(i * 2) + 1] = color;
newUV[i * 2] = new Vector2(curDistance * uvLengthScale, 0);
newUV[(i * 2) + 1] = new Vector2(curDistance * uvLengthScale, 1);
if (i > 0 && !((Point)points[i - 1]).lineBreak)
{
if (higherQualityUVs) curDistance += (p.position - ((Point)points[i - 1]).position).magnitude;
else curDistance += (p.position - ((Point)points[i - 1]).position).sqrMagnitude;
newTriangles[(i - 1) * 6] = (i * 2) - 2;
newTriangles[((i - 1) * 6) + 1] = (i * 2) - 1;
newTriangles[((i - 1) * 6) + 2] = i * 2;
newTriangles[((i - 1) * 6) + 3] = (i * 2) + 1;
newTriangles[((i - 1) * 6) + 4] = i * 2;
newTriangles[((i - 1) * 6) + 5] = (i * 2) - 1;
}
i++;
}
Mesh mesh = (o.GetComponent(typeof(MeshFilter)) as MeshFilter).mesh;
mesh.Clear();
mesh.vertices = newVertices;
mesh.colors = newColors;
mesh.uv = newUV;
mesh.triangles = newTriangles;
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Behaviours/TimedTrailRenderer.cs
|
C#
|
asf20
| 7,510
|
using UnityEngine;
using System.Collections;
public class AnimateTextureOffset : MonoBehaviour {
public Vector2 speed;
// Cache
public Material _material { get; private set; }
void Awake()
{
_material = renderer.sharedMaterial;
}
// Update is called once per frame
void Update () {
Vector2 offset = _material.GetTextureOffset("_MainTex");
offset += speed * Time.deltaTime;
_material.SetTextureOffset("_MainTex", offset);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Behaviours/AnimateTextureOffset.cs
|
C#
|
asf20
| 462
|
using System.Collections;
using System.Text;
using System.Net;
using System.IO;
using System;
using System.Threading;
namespace Framework.Network
{
public class XHttp
{
public string RequestSync(string url, string userAgent, string postData, int timeout, bool keepAlive)
{
//Header
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.KeepAlive = keepAlive;
webRequest.Timeout = timeout;
webRequest.ContentType = "application/json";
webRequest.UserAgent = userAgent;
webRequest.ContentLength = postData.Length;
//Request
using (StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
requestWriter.Flush();
requestWriter.Close();
}
//Response
using (HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse())
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
RegisteredWaitHandle handle = null;
public void RequestAsync(string url, string userAgent, string postData, int timeout, bool keepAlive, Action<string,string> requestCallBack)
{
//Header
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.UserAgent = userAgent;
webRequest.ContentLength = postData.Length;
//Async Request
webRequest.BeginGetRequestStream((req) => {
try{
//UnityEngine.Debug.Log("BeginGetRequestStream callback");
HttpWebRequest request = (HttpWebRequest)req.AsyncState;
StreamWriter requestWriter = new StreamWriter(request.EndGetRequestStream(req));
requestWriter.Write(postData);
requestWriter.Flush();
requestWriter.Close();
//Async Response
IAsyncResult aResult = webRequest.BeginGetResponse( (res) => {
try
{
//UnityEngine.Debug.Log("BeginGetResponse callback");
HttpWebRequest request2 = (HttpWebRequest)res.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request2.EndGetResponse(res);
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
requestCallBack(result,"OK");
}
catch (Exception e)
{
requestCallBack(null, e.Message);
}
},request);
handle = ThreadPool.RegisterWaitForSingleObject(aResult.AsyncWaitHandle, TimeoutCallback, webRequest, timeout, true);
}
catch(Exception e)
{
requestCallBack(null, e.Message);
}
},webRequest);
}
private void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
UnityEngine.Debug.LogError("Timeout CMNR");
HttpWebRequest req = (state as HttpWebRequest);
if (req != null)
{
req.Abort();
}
}
else
{
handle.Unregister(null);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Network/XHttp.cs
|
C#
|
asf20
| 3,649
|
using System;
using System.Text;
using System.Security.Cryptography;
namespace Framework.Network
{
public class XAes
{
private System.Text.UTF8Encoding utf8Encoding = null;
private RijndaelManaged rijndael = null;
public XAes(string key, string iv)
{
this.utf8Encoding = new System.Text.UTF8Encoding();
this.rijndael = new RijndaelManaged();
this.rijndael.Mode = CipherMode.CBC;
this.rijndael.Padding = PaddingMode.PKCS7;
this.rijndael.KeySize = 128;
this.rijndael.BlockSize = 128;
this.rijndael.Key = hex2Byte(str2Hex(key));
this.rijndael.IV = hex2Byte(str2Hex(iv));
}
public string Encrypt(string text)
{
byte[] cipherBytes = null;
ICryptoTransform transform = null;
if (text == null)
text = "";
try
{
cipherBytes = new byte[] {};
transform = this.rijndael.CreateEncryptor();
byte[] plainText = this.utf8Encoding.GetBytes(text);
cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
}
catch
{
throw new ArgumentException(
"text is not a valid string!(Encrypt)", "text");
}
return Convert.ToBase64String(cipherBytes);
}
public string Decrypt(string text)
{
byte[] plainText = null;
ICryptoTransform transform = null;
if (text == null || text == "")
throw new ArgumentException("text is not null.");
try
{
plainText = new byte[] {};
transform = rijndael.CreateDecryptor();
byte[] encryptedValue = Convert.FromBase64String(text);
plainText = transform.TransformFinalBlock(encryptedValue, 0,
encryptedValue.Length);
}
catch
{
throw new ArgumentException(
"text is not a valid string!(Decrypt)", "text");
}
return this.utf8Encoding.GetString(plainText);
}
public byte[] hex2Byte(string hex)
{
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
try
{
bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
catch
{
throw new ArgumentException(
"hex is not a valid hex number!", "hex");
}
}
return bytes;
}
public string byte2Hex(byte[] bytes)
{
string hex = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
hex += bytes[i].ToString("X2");
}
}
return hex;
}
public string str2Hex(string strData)
{
byte[] bytes = str2bytes(strData);
string resultHex = "";
foreach (byte byteStr in bytes)
{
resultHex += string.Format("{0:x2}", byteStr);
}
return resultHex;
}
public byte[] str2bytes(string byteData)
{
//System.Text.ASCIIEncoding asencoding = new System.Text.ASCIIEncoding();
return Encoding.Default.GetBytes(byteData);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Network/XAes.cs
|
C#
|
asf20
| 3,400
|
//using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
using JsonFx.Json;
namespace Framework.Network
{
/// <summary>
/// Request parameters base class
/// </summary>
public class RequestParams
{
public JSONObject ConvertToJSON()
{
JSONObject paramsList = new JSONObject(JSONObject.Type.OBJECT);
foreach (FieldInfo field in this.GetType().GetFields())
{
// UnityEngine.Debug.Log("field.Name:" + field.Name);
string val = JsonWriter.Serialize(field.GetValue(this));
paramsList.AddField(field.Name, new JSONObject(val));
}
return paramsList;
}
public string HashParams(string key)
{
StringBuilder sb = new StringBuilder();
System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create();
foreach (FieldInfo field in this.GetType().GetFields())
{
var val = field.GetValue(this).ToString();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(key + val);
byte[] hashSha256 = sha256.ComputeHash(inputBytes);
for (int i = 0; i < hashSha256.Length; i++)
{
sb.Append(hashSha256[i].ToString("X2"));
}
}
return sb.ToString();
}
}
/// <summary>
/// Response parameters. Base class
/// </summary>
public class ResponseParams
{
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Network/MessageParams.cs
|
C#
|
asf20
| 1,486
|
using UnityEngine;
using System;
using System.Collections;
public enum SGPlayerMode
{
None = -1,
Single = 0,
Multi = 1,
Online = 2
}
public class SGSystem : SingletonMono<SGSystem>
{
public System.Random randomGenerator = new System.Random((int)DateTime.Now.Ticks & 0x0000FFFF);
private bool enableCheat = true;
public float boundBottom = 0.0f;
public float boundLeft = 0.0f;
public float boundTop = 0.0f;
public float boundRight = 0.0f;
void Awake()
{
Application.targetFrameRate = 60;
Screen.sleepTimeout = SleepTimeout.NeverSleep;
}
public void CalculateBound()
{
Vector3 bottomLeft = Camera.main.ViewportToWorldPoint(new Vector3(0.0f, 0.0f, Camera.main.transform.position.y));
boundBottom = bottomLeft.z;
boundLeft = bottomLeft.x;
Vector3 topRight = Camera.main.ViewportToWorldPoint(new Vector3(1.0f, 1.0f, Camera.main.transform.position.y));
boundTop = topRight.z;
boundRight = topRight.x;
}
public bool IsEnableCheat()
{
return enableCheat;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/System/SGSystem.cs
|
C#
|
asf20
| 1,109
|
using UnityEngine;
using System.Collections;
public class StatisticDefine {
// Funnels
public const string REACH_LEVEL = "Reach Level";
// Paying Users
public const string PAY_1ST_TIME = "Pay 1ST Time";
// Payment
public const string PAY = "Pay";
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/System/StatisticDefine.cs
|
C#
|
asf20
| 263
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Interpolation utility functions: easing, bezier, and catmull-rom.
* Consider using Unity's Animation curve editor and AnimationCurve class
* before scripting the desired behaviour using this utility.
*
* Interpolation functionality available at different levels of abstraction.
* Low level access via individual easing functions (ex. EaseInOutCirc),
* Bezier(), and CatmullRom(). High level access using sequence generators,
* NewEase(), NewBezier(), and NewCatmullRom().
*
* Sequence generators are typically used as follows:
*
* IEnumerable<Vector3> sequence = Interpolate.New[Ease|Bezier|CatmulRom](configuration);
* foreach (Vector3 newPoint in sequence) {
* transform.position = newPoint;
* yield return WaitForSeconds(1.0f);
* }
*
* Or:
*
* IEnumerator<Vector3> sequence = Interpolate.New[Ease|Bezier|CatmulRom](configuration).GetEnumerator();
* function Update() {
* if (sequence.MoveNext()) {
* transform.position = sequence.Current;
* }
* }
*
* The low level functions work similarly to Unity's built in Lerp and it is
* up to you to track and pass in elapsedTime and duration on every call. The
* functions take this form (or the logical equivalent for Bezier() and CatmullRom()).
*
* transform.position = ease(start, distance, elapsedTime, duration);
*
* For convenience in configuration you can use the Ease(EaseType) function to
* look up a concrete easing function:
*
* [SerializeField]
* Interpolate.EaseType easeType; // set using Unity's property inspector
* Interpolate.Function ease; // easing of a particular EaseType
* function Awake() {
* ease = Interpolate.Ease(easeType);
* }
*
* @author Fernando Zapata (fernando@cpudreams.com)
* @Traduzione Andrea85cs (andrea85cs@dynematica.it)
*/
namespace GFramework
{
public class Interpolate
{
/**
* Different methods of easing interpolation.
*/
public enum EaseType
{
Linear,
EaseInQuad,
EaseOutQuad,
EaseInOutQuad,
EaseInCubic,
EaseOutCubic,
EaseInOutCubic,
EaseInQuart,
EaseOutQuart,
EaseInOutQuart,
EaseInQuint,
EaseOutQuint,
EaseInOutQuint,
EaseInSine,
EaseOutSine,
EaseInOutSine,
EaseInExpo,
EaseOutExpo,
EaseInOutExpo,
EaseInCirc,
EaseOutCirc,
EaseInOutCirc
}
/**
* Sequence of eleapsedTimes until elapsedTime is >= duration.
*
* Note: elapsedTimes are calculated using the value of Time.deltatTime each
* time a value is requested.
*/
static Vector3 Identity(Vector3 v)
{
return v;
}
static Vector3 TransformDotPosition(Transform t)
{
return t.position;
}
static IEnumerable<float> NewTimer(float duration)
{
float elapsedTime = 0.0f;
while (elapsedTime < duration)
{
yield return elapsedTime;
elapsedTime += Time.deltaTime;
// make sure last value is never skipped
if (elapsedTime >= duration)
{
yield return elapsedTime;
}
}
}
public delegate Vector3 ToVector3<T>(T v);
public delegate float Function(float a, float b, float c, float d);
/**
* Generates sequence of integers from start to end (inclusive) one step
* at a time.
*/
static IEnumerable<float> NewCounter(int start, int end, int step)
{
for (int i = start; i <= end; i += step)
{
yield return i;
}
}
/**
* Returns sequence generator from start to end over duration using the
* given easing function. The sequence is generated as it is accessed
* using the Time.deltaTime to calculate the portion of duration that has
* elapsed.
*/
public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float duration)
{
IEnumerable<float> timer = Interpolate.NewTimer(duration);
return NewEase(ease, start, end, duration, timer);
}
/**
* Instead of easing based on time, generate n interpolated points (slices)
* between the start and end positions.
*/
public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, int slices)
{
IEnumerable<float> counter = Interpolate.NewCounter(0, slices + 1, 1);
return NewEase(ease, start, end, slices + 1, counter);
}
/**
* Generic easing sequence generator used to implement the time and
* slice variants. Normally you would not use this function directly.
*/
static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float total, IEnumerable<float> driver)
{
Vector3 distance = end - start;
foreach (float i in driver)
{
yield return Ease(ease, start, distance, i, total);
}
}
/**
* Vector3 interpolation using given easing method. Easing is done independently
* on all three vector axis.
*/
static Vector3 Ease(Function ease, Vector3 start, Vector3 distance, float elapsedTime, float duration)
{
start.x = ease(start.x, distance.x, elapsedTime, duration);
start.y = ease(start.y, distance.y, elapsedTime, duration);
start.z = ease(start.z, distance.z, elapsedTime, duration);
return start;
}
/**
* Returns the static method that implements the given easing type for scalars.
* Use this method to easily switch between easing interpolation types.
*
* All easing methods clamp elapsedTime so that it is always <= duration.
*
* var ease = Interpolate.Ease(EaseType.EaseInQuad);
* i = ease(start, distance, elapsedTime, duration);
*/
public static Function Ease(EaseType type)
{
// Source Flash easing functions:
// http://gizma.com/easing/
// http://www.robertpenner.com/easing/easing_demo.html
//
// Changed to use more friendly variable names, that follow my Lerp
// conventions:
// start = b (start value)
// distance = c (change in value)
// elapsedTime = t (current time)
// duration = d (time duration)
Function f = null;
switch (type)
{
case EaseType.Linear: f = Interpolate.Linear; break;
case EaseType.EaseInQuad: f = Interpolate.EaseInQuad; break;
case EaseType.EaseOutQuad: f = Interpolate.EaseOutQuad; break;
case EaseType.EaseInOutQuad: f = Interpolate.EaseInOutQuad; break;
case EaseType.EaseInCubic: f = Interpolate.EaseInCubic; break;
case EaseType.EaseOutCubic: f = Interpolate.EaseOutCubic; break;
case EaseType.EaseInOutCubic: f = Interpolate.EaseInOutCubic; break;
case EaseType.EaseInQuart: f = Interpolate.EaseInQuart; break;
case EaseType.EaseOutQuart: f = Interpolate.EaseOutQuart; break;
case EaseType.EaseInOutQuart: f = Interpolate.EaseInOutQuart; break;
case EaseType.EaseInQuint: f = Interpolate.EaseInQuint; break;
case EaseType.EaseOutQuint: f = Interpolate.EaseOutQuint; break;
case EaseType.EaseInOutQuint: f = Interpolate.EaseInOutQuint; break;
case EaseType.EaseInSine: f = Interpolate.EaseInSine; break;
case EaseType.EaseOutSine: f = Interpolate.EaseOutSine; break;
case EaseType.EaseInOutSine: f = Interpolate.EaseInOutSine; break;
case EaseType.EaseInExpo: f = Interpolate.EaseInExpo; break;
case EaseType.EaseOutExpo: f = Interpolate.EaseOutExpo; break;
case EaseType.EaseInOutExpo: f = Interpolate.EaseInOutExpo; break;
case EaseType.EaseInCirc: f = Interpolate.EaseInCirc; break;
case EaseType.EaseOutCirc: f = Interpolate.EaseOutCirc; break;
case EaseType.EaseInOutCirc: f = Interpolate.EaseInOutCirc; break;
}
return f;
}
/**
* Returns sequence generator from the first node to the last node over
* duration time using the points in-between the first and last node
* as control points of a bezier curve used to generate the interpolated points
* in the sequence. If there are no control points (ie. only two nodes, first
* and last) then this behaves exactly the same as NewEase(). In other words
* a zero-degree bezier spline curve is just the easing method. The sequence
* is generated as it is accessed using the Time.deltaTime to calculate the
* portion of duration that has elapsed.
*/
public static IEnumerable<Vector3> NewBezier(Function ease, Transform[] nodes, float duration)
{
IEnumerable<float> timer = Interpolate.NewTimer(duration);
return NewBezier<Transform>(ease, nodes, TransformDotPosition, duration, timer);
}
/**
* Instead of interpolating based on time, generate n interpolated points
* (slices) between the first and last node.
*/
public static IEnumerable<Vector3> NewBezier(Function ease, Transform[] nodes, int slices)
{
IEnumerable<float> counter = NewCounter(0, slices + 1, 1);
return NewBezier<Transform>(ease, nodes, TransformDotPosition, slices + 1, counter);
}
/**
* A Vector3[] variation of the Transform[] NewBezier() function.
* Same functionality but using Vector3s to define bezier curve.
*/
public static IEnumerable<Vector3> NewBezier(Function ease, Vector3[] points, float duration)
{
IEnumerable<float> timer = NewTimer(duration);
return NewBezier<Vector3>(ease, points, Identity, duration, timer);
}
/**
* A Vector3[] variation of the Transform[] NewBezier() function.
* Same functionality but using Vector3s to define bezier curve.
*/
public static IEnumerable<Vector3> NewBezier(Function ease, Vector3[] points, int slices)
{
IEnumerable<float> counter = NewCounter(0, slices + 1, 1);
return NewBezier<Vector3>(ease, points, Identity, slices + 1, counter);
}
/**
* Generic bezier spline sequence generator used to implement the time and
* slice variants. Normally you would not use this function directly.
*/
static IEnumerable<Vector3> NewBezier<T>(Function ease, IList nodes, ToVector3<T> toVector3, float maxStep, IEnumerable<float> steps)
{
// need at least two nodes to spline between
if (nodes.Count >= 2)
{
// copy nodes array since Bezier is destructive
Vector3[] points = new Vector3[nodes.Count];
foreach (float step in steps)
{
// re-initialize copy before each destructive call to Bezier
for (int i = 0; i < nodes.Count; i++)
{
points[i] = toVector3((T)nodes[i]);
}
yield return Bezier(ease, points, step, maxStep);
// make sure last value is always generated
}
}
}
/**
* A Vector3 n-degree bezier spline.
*
* WARNING: The points array is modified by Bezier. See NewBezier() for a
* safe and user friendly alternative.
*
* You can pass zero control points, just the start and end points, for just
* plain easing. In other words a zero-degree bezier spline curve is just the
* easing method.
*
* @param points start point, n control points, end point
*/
static Vector3 Bezier(Function ease, Vector3[] points, float elapsedTime, float duration)
{
// Reference: http://ibiblio.org/e-notes/Splines/Bezier.htm
// Interpolate the n starting points to generate the next j = (n - 1) points,
// then interpolate those n - 1 points to generate the next n - 2 points,
// continue this until we have generated the last point (n - (n - 1)), j = 1.
// We store the next set of output points in the same array as the
// input points used to generate them. This works because we store the
// result in the slot of the input point that is no longer used for this
// iteration.
for (int j = points.Length - 1; j > 0; j--)
{
for (int i = 0; i < j; i++)
{
points[i].x = ease(points[i].x, points[i + 1].x - points[i].x, elapsedTime, duration);
points[i].y = ease(points[i].y, points[i + 1].y - points[i].y, elapsedTime, duration);
points[i].z = ease(points[i].z, points[i + 1].z - points[i].z, elapsedTime, duration);
}
}
return points[0];
}
/**
* Returns sequence generator from the first node, through each control point,
* and to the last node. N points are generated between each node (slices)
* using Catmull-Rom.
*/
public static IEnumerable<Vector3> NewCatmullRom(Transform[] nodes, int slices, bool loop)
{
return NewCatmullRom<Transform>(nodes, TransformDotPosition, slices, loop);
}
/**
* A Vector3[] variation of the Transform[] NewCatmullRom() function.
* Same functionality but using Vector3s to define curve.
*/
public static IEnumerable<Vector3> NewCatmullRom(Vector3[] points, int slices, bool loop)
{
return NewCatmullRom<Vector3>(points, Identity, slices, loop);
}
/**
* Generic catmull-rom spline sequence generator used to implement the
* Vector3[] and Transform[] variants. Normally you would not use this
* function directly.
*/
static IEnumerable<Vector3> NewCatmullRom<T>(IList nodes, ToVector3<T> toVector3, int slices, bool loop)
{
// need at least two nodes to spline between
if (nodes.Count >= 2)
{
// yield the first point explicitly, if looping the first point
// will be generated again in the step for loop when interpolating
// from last point back to the first point
yield return toVector3((T)nodes[0]);
int last = nodes.Count - 1;
for (int current = 0; loop || current < last; current++)
{
// wrap around when looping
if (loop && current > last)
{
current = 0;
}
// handle edge cases for looping and non-looping scenarios
// when looping we wrap around, when not looping use start for previous
// and end for next when you at the ends of the nodes array
int previous = (current == 0) ? ((loop) ? last : current) : current - 1;
int start = current;
int end = (current == last) ? ((loop) ? 0 : current) : current + 1;
int next = (end == last) ? ((loop) ? 0 : end) : end + 1;
// adding one guarantees yielding at least the end point
int stepCount = slices + 1;
for (int step = 1; step <= stepCount; step++)
{
yield return CatmullRom(toVector3((T)nodes[previous]),
toVector3((T)nodes[start]),
toVector3((T)nodes[end]),
toVector3((T)nodes[next]),
step, stepCount);
}
}
}
}
/**
* A Vector3 Catmull-Rom spline. Catmull-Rom splines are similar to bezier
* splines but have the useful property that the generated curve will go
* through each of the control points.
*
* NOTE: The NewCatmullRom() functions are an easier to use alternative to this
* raw Catmull-Rom implementation.
*
* @param previous the point just before the start point or the start point
* itself if no previous point is available
* @param start generated when elapsedTime == 0
* @param end generated when elapsedTime >= duration
* @param next the point just after the end point or the end point itself if no
* next point is available
*/
static Vector3 CatmullRom(Vector3 previous, Vector3 start, Vector3 end, Vector3 next,
float elapsedTime, float duration)
{
// References used:
// p.266 GemsV1
//
// tension is often set to 0.5 but you can use any reasonable value:
// http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf
//
// bias and tension controls:
// http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/
float percentComplete = elapsedTime / duration;
float percentCompleteSquared = percentComplete * percentComplete;
float percentCompleteCubed = percentCompleteSquared * percentComplete;
return previous * (-0.5f * percentCompleteCubed +
percentCompleteSquared -
0.5f * percentComplete) +
start * (1.5f * percentCompleteCubed +
-2.5f * percentCompleteSquared + 1.0f) +
end * (-1.5f * percentCompleteCubed +
2.0f * percentCompleteSquared +
0.5f * percentComplete) +
next * (0.5f * percentCompleteCubed -
0.5f * percentCompleteSquared);
}
/**
* Linear interpolation (same as Mathf.Lerp)
*/
static float Linear(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime to be <= duration
if (elapsedTime > duration) { elapsedTime = duration; }
return distance * (elapsedTime / duration) + start;
}
/**
* quadratic easing in - accelerating from zero velocity
*/
static float EaseInQuad(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
return distance * elapsedTime * elapsedTime + start;
}
/**
* quadratic easing out - decelerating to zero velocity
*/
static float EaseOutQuad(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
return -distance * elapsedTime * (elapsedTime - 2) + start;
}
/**
* quadratic easing in/out - acceleration until halfway, then deceleration
*/
static float EaseInOutQuad(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2);
if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime + start;
elapsedTime--;
return -distance / 2 * (elapsedTime * (elapsedTime - 2) - 1) + start;
}
/**
* cubic easing in - accelerating from zero velocity
*/
static float EaseInCubic(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
return distance * elapsedTime * elapsedTime * elapsedTime + start;
}
/**
* cubic easing out - decelerating to zero velocity
*/
static float EaseOutCubic(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
elapsedTime--;
return distance * (elapsedTime * elapsedTime * elapsedTime + 1) + start;
}
/**
* cubic easing in/out - acceleration until halfway, then deceleration
*/
static float EaseInOutCubic(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2);
if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime + start;
elapsedTime -= 2;
return distance / 2 * (elapsedTime * elapsedTime * elapsedTime + 2) + start;
}
/**
* quartic easing in - accelerating from zero velocity
*/
static float EaseInQuart(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start;
}
/**
* quartic easing out - decelerating to zero velocity
*/
static float EaseOutQuart(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
elapsedTime--;
return -distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 1) + start;
}
/**
* quartic easing in/out - acceleration until halfway, then deceleration
*/
static float EaseInOutQuart(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2);
if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start;
elapsedTime -= 2;
return -distance / 2 * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 2) + start;
}
/**
* quintic easing in - accelerating from zero velocity
*/
static float EaseInQuint(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start;
}
/**
* quintic easing out - decelerating to zero velocity
*/
static float EaseOutQuint(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
elapsedTime--;
return distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 1) + start;
}
/**
* quintic easing in/out - acceleration until halfway, then deceleration
*/
static float EaseInOutQuint(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2f);
if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start;
elapsedTime -= 2;
return distance / 2 * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 2) + start;
}
/**
* sinusoidal easing in - accelerating from zero velocity
*/
static float EaseInSine(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime to be <= duration
if (elapsedTime > duration) { elapsedTime = duration; }
return -distance * Mathf.Cos(elapsedTime / duration * (Mathf.PI / 2)) + distance + start;
}
/**
* sinusoidal easing out - decelerating to zero velocity
*/
static float EaseOutSine(float start, float distance, float elapsedTime, float duration)
{
if (elapsedTime > duration) { elapsedTime = duration; }
return distance * Mathf.Sin(elapsedTime / duration * (Mathf.PI / 2)) + start;
}
/**
* sinusoidal easing in/out - accelerating until halfway, then decelerating
*/
static float EaseInOutSine(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime to be <= duration
if (elapsedTime > duration) { elapsedTime = duration; }
return -distance / 2 * (Mathf.Cos(Mathf.PI * elapsedTime / duration) - 1) + start;
}
/**
* exponential easing in - accelerating from zero velocity
*/
static float EaseInExpo(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime to be <= duration
if (elapsedTime > duration) { elapsedTime = duration; }
return distance * Mathf.Pow(2, 10 * (elapsedTime / duration - 1)) + start;
}
/**
* exponential easing out - decelerating to zero velocity
*/
static float EaseOutExpo(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime to be <= duration
if (elapsedTime > duration) { elapsedTime = duration; }
return distance * (-Mathf.Pow(2, -10 * elapsedTime / duration) + 1) + start;
}
/**
* exponential easing in/out - accelerating until halfway, then decelerating
*/
static float EaseInOutExpo(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2);
if (elapsedTime < 1) return distance / 2 * Mathf.Pow(2, 10 * (elapsedTime - 1)) + start;
elapsedTime--;
return distance / 2 * (-Mathf.Pow(2, -10 * elapsedTime) + 2) + start;
}
/**
* circular easing in - accelerating from zero velocity
*/
static float EaseInCirc(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
return -distance * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) - 1) + start;
}
/**
* circular easing out - decelerating to zero velocity
*/
static float EaseOutCirc(float start, float distance, float elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration;
elapsedTime--;
return distance * Mathf.Sqrt(1 - elapsedTime * elapsedTime) + start;
}
/**
* circular easing in/out - acceleration until halfway, then deceleration
*/
static float EaseInOutCirc(float start, float distance, float
elapsedTime, float duration)
{
// clamp elapsedTime so that it cannot be greater than duration
elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2);
if (elapsedTime < 1) return -distance / 2 * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) - 1) + start;
elapsedTime -= 2;
return distance / 2 * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) + 1) + start;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/Interpolate.cs
|
C#
|
asf20
| 25,755
|
using UnityEngine;
/// <summary>
/// Screen positions for use with the ScreenPlacement transform and gameObject extension for the 9 positions around the screen edge.
/// </summary>
public enum ScreenPosition {UpperLeft, UpperMiddle, UpperRight, Left, Middle, Right, LowerLeft, LowerMiddle, LowerRight};
public static class ScreenPlacementExtension{
//Add instructions
//GameObject overrides:
/// <summary>
/// Places a GameObject at one of the 9 positions around the screen edge.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/>
/// </param>
/// <param name="position">
/// A <see cref="ScreenPosition"/>
/// </param>
public static void ScreenPlacement(this GameObject target, ScreenPosition position){
DoScreenPlacement(target.transform, position, Vector2.zero, Camera.main);
}
/// <summary>
/// Places a GameObject at one of the 9 positions around the screen edge.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/>
/// </param>
/// <param name="position">
/// A <see cref="ScreenPosition"/>
/// </param>
/// <param name="renderingCamera">
/// A <see cref="Camera"/>
/// </param>
public static void ScreenPlacement(this GameObject target, ScreenPosition position, Camera renderingCamera){
DoScreenPlacement(target.transform, position, Vector2.zero, renderingCamera);
}
/// <summary>
/// Places a GameObject at one of the 9 positions around the screen edge.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/>
/// </param>
/// <param name="position">
/// A <see cref="ScreenPosition"/>
/// </param>
/// <param name="pixelsFromEdge">
/// A <see cref="Vector2"/>
/// </param>
public static void ScreenPlacement(this GameObject target, ScreenPosition position, Vector2 pixelsFromEdge){
DoScreenPlacement(target.transform, position, pixelsFromEdge, Camera.main);
}
/// <summary>
/// Places a GameObject at one of the 9 positions around the screen edge.
/// </summary>
/// <param name="target">
/// A <see cref="GameObject"/>
/// </param>
/// <param name="position">
/// A <see cref="ScreenPosition"/>
/// </param>
/// <param name="pixelsFromEdge">
/// A <see cref="Vector2"/>
/// </param>
/// <param name="renderingCamera">
/// A <see cref="Camera"/>
/// </param>
public static void ScreenPlacement(this GameObject target, ScreenPosition position, Vector2 pixelsFromEdge, Camera renderingCamera){
DoScreenPlacement(target.transform, position, pixelsFromEdge, renderingCamera);
}
//Transform overrides:
/// <summary>
/// Places a Transform at one of the 9 positions around the screen edge.
/// </summary>
/// <param name="target">
/// A <see cref="Transform"/>
/// </param>
/// <param name="position">
/// A <see cref="ScreenPosition"/>
/// </param>
public static void ScreenPlacement(this Transform target, ScreenPosition position){
DoScreenPlacement(target.transform, position, Vector2.zero, Camera.main);
}
/// <summary>
/// Places a Transform at one of the 9 positions around the screen edge.
/// </summary>
/// <param name="target">
/// A <see cref="Transform"/>
/// </param>
/// <param name="position">
/// A <see cref="ScreenPosition"/>
/// </param>
/// <param name="renderingCamera">
/// A <see cref="Camera"/>
/// </param>
public static void ScreenPlacement(this Transform target, ScreenPosition position, Camera renderingCamera){
DoScreenPlacement(target.transform, position, Vector2.zero, renderingCamera);
}
/// <summary>
/// Places a Transform at one of the 9 positions around the screen edge.
/// </summary>
/// <param name="target">
/// A <see cref="Transform"/>
/// </param>
/// <param name="position">
/// A <see cref="ScreenPosition"/>
/// </param>
/// <param name="pixelsFromEdge">
/// A <see cref="Vector2"/>
/// </param>
public static void ScreenPlacement(this Transform target, ScreenPosition position, Vector2 pixelsFromEdge){
DoScreenPlacement(target.transform, position, pixelsFromEdge, Camera.main);
}
/// <summary>
/// Places a Transform at one of the 9 positions around the screen edge.
/// </summary>
/// <param name="target">
/// A <see cref="Transform"/>
/// </param>
/// <param name="position">
/// A <see cref="ScreenPosition"/>
/// </param>
/// <param name="pixelsFromEdge">
/// A <see cref="Vector2"/>
/// </param>
/// <param name="renderingCamera">
/// A <see cref="Camera"/>
/// </param>
public static void ScreenPlacement(this Transform target, ScreenPosition position, Vector2 pixelsFromEdge, Camera renderingCamera){
DoScreenPlacement(target.transform, position, pixelsFromEdge, renderingCamera);
}
//Placement execution:
private static void DoScreenPlacement(this Transform target, ScreenPosition position, Vector2 pixelsFromEdge, Camera renderingCamera){
Vector3 screenPosition = Vector3.zero;
float zPosition = -renderingCamera.transform.position.z + target.position.z;
switch (position) {
//uppers:
case ScreenPosition.UpperLeft:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3(pixelsFromEdge.x, Screen.height-pixelsFromEdge.y, zPosition));
break;
case ScreenPosition.UpperMiddle:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3(Screen.width/2, Screen.height-pixelsFromEdge.y, zPosition));
break;
case ScreenPosition.UpperRight:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3(Screen.width-pixelsFromEdge.x, Screen.height-pixelsFromEdge.y, zPosition));
break;
//mids:
case ScreenPosition.Left:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3(pixelsFromEdge.x, Screen.height/2, zPosition));
break;
case ScreenPosition.Middle:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3((Screen.width/2) + pixelsFromEdge.x, (Screen.height/2) + pixelsFromEdge.y, zPosition));
break;
case ScreenPosition.Right:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3(Screen.width-pixelsFromEdge.x, Screen.height/2, zPosition));
break;
//lowers:
case ScreenPosition.LowerLeft:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3(pixelsFromEdge.x, pixelsFromEdge.y, zPosition));
break;
case ScreenPosition.LowerMiddle:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3(Screen.width/2, pixelsFromEdge.y, zPosition));
break;
case ScreenPosition.LowerRight:
screenPosition = renderingCamera.ScreenToWorldPoint(new Vector3(Screen.width-pixelsFromEdge.x, pixelsFromEdge.y, zPosition));
break;
}
target.transform.position = screenPosition;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ScreenPlacementExtension.cs
|
C#
|
asf20
| 6,632
|
using UnityEngine;
using System.Collections;
using GFramework;
using System;
public class SystemHelper {
private static string _deviceUniqueID;
public static string deviceUniqueID
{
get
{
try
{
if (_deviceUniqueID == null)
computeDeviceUniqueID();
}
catch (Exception ex)
{
_deviceUniqueID = "Default";
}
return _deviceUniqueID;
}
}
private static void computeDeviceUniqueID()
{
string systemID = "";
systemID = SystemInfo.deviceUniqueIdentifier;
_deviceUniqueID = systemID.Replace("-", "").ToLower();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/SystemHelper.cs
|
C#
|
asf20
| 693
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace GFramework
{
public class Layout
{
public class Scroll : IDisposable
{
bool _disposed = false;
private Scroll()
{
}
public static Scroll ScrollView(ref Vector2 scrollPosition)
{
Scroll scrl = new Scroll();
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
return scrl;
}
public static Scroll ScrollView(ref Vector2 scrollPosition, GUIStyle style)
{
Scroll scrl = new Scroll();
scrollPosition = GUILayout.BeginScrollView(scrollPosition, style);
return scrl;
}
public static Scroll ScrollView(ref Vector2 scrollPosition, params GUILayoutOption[] options)
{
Scroll scrl = new Scroll();
scrollPosition = GUILayout.BeginScrollView(scrollPosition, options);
return scrl;
}
public static Scroll ScrollView(ref Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, params GUILayoutOption[] options)
{
Scroll scrl = new Scroll();
scrollPosition = GUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, options);
return scrl;
}
public static Scroll ScrollView(ref Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options)
{
Scroll scrl = new Scroll();
scrollPosition = GUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, options);
return scrl;
}
public static Scroll ScrollView(ref Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options)
{
Scroll scrl = new Scroll();
scrollPosition = GUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background, options);
return scrl;
}
public void Dispose()
{
if (_disposed) return;
GUILayout.EndScrollView();
_disposed = true;
}
}
public class SetColor : IDisposable
{
bool _disposed = false;
private readonly Color _color;
public SetColor(Color color)
{
_color = GUI.color;
GUI.color = color;
}
public void Dispose()
{
if (_disposed) return;
GUI.color = _color;
_disposed = true;
}
}
public class GUIEnabled : IDisposable
{
bool _disposed = false;
private readonly bool _enabled;
public GUIEnabled(bool enabled)
{
_enabled = GUI.enabled;
GUI.enabled = enabled;
}
public void Dispose()
{
if (_disposed) return;
GUI.enabled = _enabled;
_disposed = true;
}
}
public class Horizontal : IDisposable
{
bool _disposed = false;
public Horizontal()
{
GUILayout.BeginHorizontal();
}
public Horizontal(params GUILayoutOption[] options)
{
GUILayout.BeginHorizontal(options);
}
public Horizontal(GUIStyle style, params GUILayoutOption[] options)
{
GUILayout.BeginHorizontal(style, options);
}
public void Dispose()
{
if (_disposed) return;
GUILayout.EndHorizontal();
_disposed = true;
}
}
public class AlignToCenter : IDisposable
{
bool _disposed = false;
public AlignToCenter()
{
GUILayout.FlexibleSpace();
}
public void Dispose()
{
if (_disposed) return;
GUILayout.FlexibleSpace();
_disposed = true;
}
}
public class Vertical : IDisposable
{
bool _disposed = false;
public Vertical()
{
GUILayout.BeginVertical();
}
public Vertical(params GUILayoutOption[] options)
{
GUILayout.BeginHorizontal(options);
}
public Vertical(GUIStyle style, params GUILayoutOption[] options)
{
GUILayout.BeginVertical(style, options);
}
public void Dispose()
{
if (_disposed) return;
GUILayout.EndVertical();
_disposed = true;
}
}
public class Area : IDisposable
{
bool _disposed = false;
public Area(Rect rect)
{
GUILayout.BeginArea(rect);
}
public void Dispose()
{
if (_disposed) return;
GUILayout.EndArea();
_disposed = true;
}
}
#if UNITY_EDITOR
/// <summary>
/// Display a session header
/// </summary>
public static void EditorSessionHeader(string name)
{
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
GUILayout.Label(name, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false));
GUILayout.Box("", EditorStyles.toolbar, GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal();
}
/// <summary>
/// Display a toogle session header
/// </summary>
public static bool EditorSessionHeaderToogle(string name, bool toogle)
{
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
if (GUILayout.Button(name, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
toogle = !toogle;
GUILayout.Box("", EditorStyles.toolbar, GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal();
return toogle;
}
#endif
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/LayoutHelper.cs
|
C#
|
asf20
| 6,647
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using System.Reflection;
namespace GFramework
{
public interface IConfigDataTable
{
/// <summary>
/// Get name
/// </summary>
string GetName();
/// <summary>
/// Begin append load
/// </summary>
void BeginLoadAppend();
/// <summary>
/// Begin append load
/// </summary>
void EndLoadAppend();
/// <summary>
/// Load data from string from memory
/// </summary>
void LoadFromString(string content);
/// <summary>
/// Load data from a text asset
/// </summary>
void LoadFromAsset(TextAsset asset);
/// <summary>
/// Load data from a text asset path
/// </summary>
void LoadFromAssetPath(string assetPath);
/// <summary>
/// Clear all data
/// </summary>
void Clear();
}
public class GConfigDataTable<TDataRecord> : IConfigDataTable, IEnumerable<TDataRecord> where TDataRecord : class
{
// Index fields
public class IndexField<TIndex> : Dictionary<TIndex, object> { };
// Record list
public List<TDataRecord> records { get; private set; }
// Indices lookup
private Dictionary<string, object> indices;
// Name
public string name { get; private set; }
// Is loaded
public bool isLoaded { get; private set; }
// Is empty
public bool isEmpty { get { return records.Count == 0; } }
// Get num records
public int count { get { return records.Count; } }
// Flag to mark append loading
private bool isAppendLoading = false;
/// <summary>
/// Constructor
/// </summary>
public GConfigDataTable()
{
this.name = GetType().Name;
records = new List<TDataRecord>();
}
/// <summary>
/// Constructor
/// </summary>
public GConfigDataTable(string name)
{
this.name = name;
records = new List<TDataRecord>();
}
/// <summary>
///
/// </summary>
protected virtual void OnDataLoaded()
{
}
/// <summary>
/// Get name
/// </summary>
public string GetName()
{
return name;
}
public void BeginLoadAppend()
{
isAppendLoading = true;
}
public void EndLoadAppend()
{
if (isAppendLoading)
{
isLoaded = true;
OnDataLoaded();
isAppendLoading = false;
}
}
/// <summary>
/// Load data from string from memory
/// </summary>
public void LoadFromString(string content)
{
if (string.IsNullOrEmpty(content))
throw new ArgumentException("Content is null or empty");
if (!isAppendLoading && isLoaded)
Clear();
FileHelpers.FileHelperEngine fileEngine = new FileHelpers.FileHelperEngine(typeof(TDataRecord));
records.AddRange(fileEngine.ReadString(content).Select(r => r as TDataRecord));
if (!isAppendLoading)
{
isLoaded = true;
OnDataLoaded();
}
}
/// <summary>
/// Load data from a text asset
/// </summary>
public void LoadFromAsset(TextAsset asset)
{
if (asset == null)
throw new ArgumentNullException("Asset data is invalid");
LoadFromString(asset.text);
}
/// <summary>
/// Load data from a text asset path
/// </summary>
public void LoadFromAssetPath(string assetPath)
{
if( string.IsNullOrEmpty(assetPath) )
throw new ArgumentException("Asset path is null or empty");
LoadFromAsset(Resources.Load(assetPath) as TextAsset);
}
/// <summary>
/// Clear all data
/// </summary>
public void Clear()
{
records.Clear();
isLoaded = false;
}
/// <summary>
/// Build index from a table field
/// </summary>
public void RebuildIndexField<TIndex>(string fieldName)
{
if (isEmpty)
return;
// Search field name by reflection
Type recordType = typeof(TDataRecord);
// Check the record type to find the field you need to indexed
FieldInfo fieldInfo = recordType.GetField(fieldName);
if (fieldInfo == null)
throw new Exception("Field [" + fieldName + "] not found");
if (indices == null)
indices = new Dictionary<string, object>();
// Add new index column object
IndexField<TIndex> indexField = new IndexField<TIndex>();
indices[fieldName] = indexField;
// Build index column field from records
for (int i = 0; i < records.Count; i++)
{
// Get field value
var fieldValue = (TIndex) fieldInfo.GetValue(records[i]);
// the value of the index maybe a single record or a list of records that have the same key field
object indexedValue;
if (!indexField.TryGetValue(fieldValue, out indexedValue))
indexField.Add(fieldValue, records[i]);
else
{
// If indexedValue is a list, append data
if (indexedValue is List<TDataRecord>)
(indexedValue as List<TDataRecord>).Add(records[i]);
else
{
var listRecords = new List<TDataRecord>();
listRecords.Add(indexedValue as TDataRecord);
listRecords.Add(records[i]);
indexField[fieldValue] = listRecords;
}
}
}
}
/// <summary>
/// Check if the field is indexed
/// </summary>
public bool IsFieldIndexed(string fieldName)
{
if (indices == null)
return false;
return indices.ContainsKey(fieldName);
}
/// <summary>
///
/// </summary>
private TDataRecord FindRecordByIndex<TIndex>(object _indexField, TIndex value)
{
var indexField = _indexField as IndexField<TIndex>;
if (indexField == null)
throw new InvalidOperationException("Index type and search key mismatch");
// Find
object indexedValue;
if (!indexField.TryGetValue(value, out indexedValue))
return null;
// Get first item in the list
if (indexedValue is List<TDataRecord>)
return (indexedValue as List<TDataRecord>).FirstOrDefault() as TDataRecord;
return indexedValue as TDataRecord;
}
/// <summary>
///
/// </summary>
private List<TDataRecord> FindRecordsByIndex<TIndex>(object _indexField, TIndex value)
{
var indexField = _indexField as IndexField<TIndex>;
if (indexField == null)
throw new InvalidOperationException("Index type mismatch");
// Find
object indexedValue;
if (!indexField.TryGetValue(value, out indexedValue))
return null;
// Get first item in the list
if (indexedValue is List<TDataRecord>)
return indexedValue as List<TDataRecord>;
return new List<TDataRecord>() { indexedValue as TDataRecord };
}
/// <summary>
/// Find single record of a index
/// </summary>
public TDataRecord FindRecordByIndex<TIndex>(string indexName, TIndex value)
{
// Do not have index
object indexField;
if (indices == null || !indices.TryGetValue(indexName, out indexField))
{
if (null != indexName && indexName.Length > 0)
throw new InvalidOperationException("Index not found 1: " + indexName);
else
throw new InvalidOperationException("Index not found 1.");
}
return FindRecordByIndex<TIndex>(indexField, value);
}
/// <summary>
/// Find many records of a index
/// </summary>
public List<TDataRecord> FindRecordsByIndex<TIndex>(string indexName, TIndex value)
{
// Do not have index
object indexField;
if (indices == null || !indices.TryGetValue(indexName, out indexField))
{
if (null != indexName && indexName.Length > 0)
throw new InvalidOperationException("Index not found 2" + indexName);
else
throw new InvalidOperationException("Index not found 2.");
}
return FindRecordsByIndex<TIndex>(indexField, value);
}
#region IEnumerable<TDataRecord> Members
public IEnumerator<TDataRecord> GetEnumerator()
{
return records.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return records.GetEnumerator();
}
#endregion
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ConfigDataTable.cs
|
C#
|
asf20
| 8,048
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using UnityEngine;
namespace GFramework
{
public class XmlHelper
{
public static Quaternion ToQuaternion(XmlNode node)
{
return new Quaternion(XmlConvert.ToSingle(node.Attributes["x"].Value), XmlConvert.ToSingle(node.Attributes["y"].Value), XmlConvert.ToSingle(node.Attributes["z"].Value), XmlConvert.ToSingle(node.Attributes["w"].Value));
}
public static Vector3 ToVector3(XmlNode node)
{
return new Vector3(XmlConvert.ToSingle(node.Attributes["x"].Value), XmlConvert.ToSingle(node.Attributes["y"].Value), XmlConvert.ToSingle(node.Attributes["z"].Value));
}
/* public static T XmlDeserialize<T>(DataWarehouse data) where T: class
{
return XmlDeserialize<T>(data, new XmlSerializer(typeof(T)));
}*/
public static T XmlDeserialize<T>(string xml)
{
using (StringReader reader = new StringReader(xml))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(reader);
}
}
public static T XmlDeserialize<T>(XmlReader xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(xml);
}
/* public static T XmlDeserialize<T>(DataWarehouse data, XmlSerializer serializer) where T: class
{
return (serializer.Deserialize(data.Navigator.ReadSubtree()) as T);
}*/
public static T XmlDeserializeElement<T>(XmlReader xml, string element)
{
xml.ReadStartElement(element);
T local = XmlDeserialize<T>(xml);
xml.ReadEndElement();
return local;
}
public static T XmlDeserializeInner<T>(string innerXml)
{
return XmlDeserializeInner<T>(innerXml, new XmlSerializer(typeof(T)));
}
public static T XmlDeserializeInner<T>(string innerXml, XmlSerializer serializer)
{
string elementName = null;
Attribute[] customAttributes = Attribute.GetCustomAttributes(typeof(T), typeof(XmlRootAttribute));
if ((customAttributes != null) && (customAttributes.Length > 0))
{
elementName = ((XmlRootAttribute)customAttributes[0]).ElementName;
}
else
{
elementName = typeof(T).Name;
}
string s = string.Format("<{0}>{1}</{0}>", elementName, innerXml);
return (T)serializer.Deserialize(new StringReader(s));
}
public static T XmlDeserializeValue<T>(XmlReader xml, string element, T def)
{
try
{
xml.ReadStartElement(element);
T local = (T)xml.ReadContentAs(typeof(T), null);
xml.ReadEndElement();
return local;
}
catch
{
return def;
}
}
public static T XmlReadAttribute<T>(XmlReader xml, string attribute, T def)
{
xml.MoveToAttribute(attribute);
T local = (T)xml.ReadContentAs(typeof(T), null);
xml.MoveToElement();
return local;
}
public static void XmlSerialize<T>(XmlWriter xml, T obj)
{
new XmlSerializer(typeof(T)).Serialize(xml, obj);
}
public static void XmlSerializeElement<T>(XmlWriter xml, string element, T obj)
{
xml.WriteStartElement(element);
XmlSerialize<T>(xml, obj);
xml.WriteEndElement();
}
public static void XmlSerializeValue(XmlWriter xml, string element, Quaternion q)
{
xml.WriteStartElement(element);
XmlWriteAttribute<double>(xml, "x", (double)q.x);
XmlWriteAttribute<double>(xml, "y", (double)q.y);
XmlWriteAttribute<double>(xml, "z", (double)q.z);
XmlWriteAttribute<double>(xml, "w", (double)q.w);
xml.WriteEndElement();
}
public static void XmlSerializeValue(XmlWriter xml, string element, Vector2 v)
{
xml.WriteStartElement(element);
XmlWriteAttribute<double>(xml, "x", (double)v.x);
XmlWriteAttribute<double>(xml, "y", (double)v.y);
xml.WriteEndElement();
}
public static void XmlSerializeValue<T>(XmlWriter xml, string element, T obj)
{
xml.WriteStartElement(element);
xml.WriteValue(obj);
xml.WriteEndElement();
}
public static void XmlSerializeValue(XmlWriter xml, string element, Vector3 v)
{
xml.WriteStartElement(element);
XmlWriteAttribute<double>(xml, "x", (double)v.x);
XmlWriteAttribute<double>(xml, "y", (double)v.y);
XmlWriteAttribute<double>(xml, "z", (double)v.z);
xml.WriteEndElement();
}
public static void XmlSerializeValue(XmlWriter xml, string element, Vector4 v)
{
xml.WriteStartElement(element);
XmlWriteAttribute<double>(xml, "x", (double)v.x);
XmlWriteAttribute<double>(xml, "y", (double)v.y);
XmlWriteAttribute<double>(xml, "z", (double)v.z);
XmlWriteAttribute<double>(xml, "w", (double)v.w);
xml.WriteEndElement();
}
public static void XmlWriteAttribute<T>(XmlWriter xml, string attribute, T value)
{
xml.WriteStartAttribute(attribute);
xml.WriteValue(value);
xml.WriteEndAttribute();
}
public static void XmlWriteAttribute(XmlWriter xml, string attribute, float value)
{
XmlWriteAttribute<double>(xml, attribute, (double)value);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/XmlHelper.cs
|
C#
|
asf20
| 5,146
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
public class LeakCounter
{
public int allCounters;
public Dictionary<string, int> objectInstances = new Dictionary<string, int>();
public List<KeyValuePair<string, int>> sortedObjectInstances;
}
public class DetectLeaks : MonoBehaviour
{
private Vector2 scrollPos = Vector2.zero;
private Vector2 scrollSubPos = Vector2.zero;
private Dictionary<Type, LeakCounter> objectTypes = new Dictionary<Type, LeakCounter>();
private List<KeyValuePair<Type, LeakCounter>> sortedObjectTypes;
private Type currentShowType;
void Start()
{
StartCoroutine(UpdateInfo());
}
IEnumerator UpdateInfo()
{
while(true)
{
// Clear
foreach (var type in objectTypes)
{
type.Value.allCounters = 0;
if (type.Value.objectInstances != null)
{
foreach (var ins in type.Value.objectInstances.Keys.ToArray())
type.Value.objectInstances[ins] = 0;
}
type.Value.sortedObjectInstances = null;
}
// Count
UnityEngine.Object[] objects = FindObjectsOfType(typeof(UnityEngine.Object));
foreach (UnityEngine.Object obj in objects)
{
Type key = obj.GetType();
LeakCounter counter = null;
if (!objectTypes.TryGetValue(key, out counter) || counter == null)
{
counter = new LeakCounter();
objectTypes[key] = counter;
}
counter.allCounters++;
if (counter.objectInstances == null)
counter.objectInstances = new Dictionary<string, int>();
if (!counter.objectInstances.ContainsKey(obj.name))
counter.objectInstances.Add(obj.name, 0);
counter.objectInstances[obj.name]++;
}
// Sort type counter
sortedObjectTypes = new List<KeyValuePair<Type, LeakCounter>>(objectTypes);
sortedObjectTypes.Sort(
delegate(KeyValuePair<Type, LeakCounter> firstPair, KeyValuePair<Type, LeakCounter> nextPair)
{
return nextPair.Value.allCounters.CompareTo(firstPair.Value.allCounters);
}
);
// Sort instance counter
foreach (var type in objectTypes)
{
type.Value.sortedObjectInstances = new List<KeyValuePair<string, int>>(type.Value.objectInstances);
type.Value.sortedObjectInstances.Sort(
delegate(KeyValuePair<string, int> firstPair, KeyValuePair<string, int> nextPair)
{
return nextPair.Value.CompareTo(firstPair.Value);
}
);
}
yield return new WaitForSeconds(1.0f);
}
}
void OnGUI()
{
if (sortedObjectTypes == null)
return;
GUILayout.BeginHorizontal();
scrollPos = GUILayout.BeginScrollView(scrollPos, false, true, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.box);
foreach (KeyValuePair<Type, LeakCounter> entry in sortedObjectTypes)
{
GUILayout.BeginHorizontal();
if (GUILayout.Toggle(currentShowType == entry.Key, "", GUILayout.Width(18)))
currentShowType = entry.Key;
GUILayout.Label(entry.Key.ToString() + ": ", GUILayout.Width(200));
GUILayout.Label("" + entry.Value.allCounters, GUILayout.Width(40));
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
if (currentShowType != null)
{
LeakCounter currentCounter = null;
if (!objectTypes.TryGetValue(currentShowType, out currentCounter) || currentCounter == null || currentCounter.sortedObjectInstances == null)
return;
scrollSubPos = GUILayout.BeginScrollView(scrollSubPos, false, true, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.box);
foreach (KeyValuePair<string, int> entry2 in currentCounter.sortedObjectInstances)
{
GUILayout.BeginHorizontal();
GUILayout.Label(entry2.Key + ": ", GUILayout.Width(200));
GUILayout.Label("" + entry2.Value, GUILayout.Width(40));
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/DetectLeaks.cs
|
C#
|
asf20
| 3,991
|
using UnityEngine;
using System;
namespace GFramework
{
struct VertexData
{
// Pointers to vertex data
public Vector3[] positions;
public Vector3[] normals;
public BoneWeight[] boneWeights;
public Color[] colors;
public Vector2[] uv;
public Vector2[] uv1;
public Vector2[] uv2;
public Vector4[] tangents;
};
[Flags]
public enum VertexFormat : long
{
Position = 0x01,
Normal = 0x02,
BoneWeight = 0x04,
Color = 0x08,
UV = 0x10,
UV1 = 0x20,
UV2 = 0x40,
Tangent = 0x80,
LitDiffuse = Position | Normal | Color,
UnlitDiffuse = Position | Color,
LitTexture = Position | Normal | UV,
UnlitTexture = Position | UV,
LitDiffuseTexture = Position | Normal | Color | UV,
UnlitDiffuseTexture = Position | Color | UV,
};
public class MeshBuilder
{
// Current mesh desc
private VertexData vertices;
private int[] indices;
// Num indices and vertices is allowed to modify
private int numVertices;
private int numIndices;
// First vertex index
private int firstVertexIndex;
// The current vertex and index
private int curVertex;
private int curIndex;
// Vertex format
public VertexFormat VertFormat { get; protected set; }
// Is lock to modify
private bool isLocked;
public MeshBuilder()
{
}
~MeshBuilder()
{
}
public bool vertexHasComponent(VertexFormat format)
{
return (this.VertFormat & format) == format;
}
/// <summary>
///
/// </summary>
/// <param name="mesh"></param>
/// <param name="numVertices"></param>
public void beginOverwrite( VertexFormat vertFormat, int numVertices, int numTriangles )
{
isLocked = true;
// Vertex format
this.VertFormat = vertFormat | VertexFormat.Position;
// Number
this.firstVertexIndex = 0;
this.numVertices = numVertices;
this.numIndices = numTriangles * 3;
// Data
this.vertices.positions = new Vector3[this.numVertices];
if (vertexHasComponent(VertexFormat.Normal))
this.vertices.normals = new Vector3[this.numVertices];
if (vertexHasComponent(VertexFormat.BoneWeight))
this.vertices.boneWeights = new BoneWeight[this.numVertices];
if (vertexHasComponent(VertexFormat.Color))
this.vertices.colors = new Color[this.numVertices];
if (vertexHasComponent(VertexFormat.UV))
this.vertices.uv = new Vector2[this.numVertices];
if (vertexHasComponent(VertexFormat.UV1))
this.vertices.uv1 = new Vector2[this.numVertices];
if (vertexHasComponent(VertexFormat.UV2))
this.vertices.uv2 = new Vector2[this.numVertices];
if (vertexHasComponent(VertexFormat.Tangent))
this.vertices.tangents = new Vector4[this.numVertices];
this.indices = new int[this.numIndices];
// reset to begin of buffer
reset( 0, 0 );
}
public void end()
{
isLocked = false;
}
/// <summary>
///
/// </summary>
/// <param name="mesh"></param>
/// <param name="numVertices"></param>
/// <param name="firstVertex"></param>
/// <param name="numIndices"></param>
/// <param name="firstIndex"></param>
public void beginUpdate( Mesh mesh, int firstVertex, int firstIndex )
{
isLocked = true;
this.VertFormat = 0;
this.firstVertexIndex = 0;
this.vertices.positions = mesh.vertices;
this.vertices.normals = mesh.normals;
if (this.vertices.normals != null)
this.VertFormat |= VertexFormat.Normal;
this.vertices.boneWeights = mesh.boneWeights;
if (this.vertices.boneWeights != null)
this.VertFormat |= VertexFormat.BoneWeight;
this.vertices.colors = mesh.colors;
if (this.vertices.colors != null)
this.VertFormat |= VertexFormat.Color;
this.vertices.uv = mesh.uv;
if (this.vertices.uv != null)
this.VertFormat |= VertexFormat.UV;
this.vertices.uv1 = mesh.uv1;
if (this.vertices.uv1 != null)
this.VertFormat |= VertexFormat.UV1;
this.vertices.uv2 = mesh.uv2;
if (this.vertices.uv2 != null)
this.VertFormat |= VertexFormat.UV2;
this.vertices.tangents = mesh.tangents;
if (this.vertices.tangents != null)
this.VertFormat |= VertexFormat.Tangent;
this.indices = mesh.triangles;
this.numVertices = this.vertices.positions.Length;
this.numIndices = this.indices.Length;
// reset to begin of buffer
reset(firstVertex, firstIndex);
}
public void beginAppend(VertexFormat vertFormat, int numVertices, int numTriangles)
{
if (this.numVertices == 0)
{
beginOverwrite(vertFormat, numVertices, numTriangles);
return;
}
isLocked = true;
// reset to begin of buffer
reset(this.numVertices, this.numIndices);
// Number
this.firstVertexIndex = this.numVertices;
this.numVertices += numVertices;
this.numIndices += numTriangles * 3;
// Data
Array.Resize(ref this.vertices.positions, this.numVertices);
if (vertexHasComponent(VertexFormat.Normal))
Array.Resize(ref this.vertices.normals, this.numVertices);
if (vertexHasComponent(VertexFormat.BoneWeight))
Array.Resize(ref this.vertices.boneWeights, this.numVertices);
if (vertexHasComponent(VertexFormat.Color))
Array.Resize(ref this.vertices.colors, this.numVertices);
if (vertexHasComponent(VertexFormat.UV))
Array.Resize(ref this.vertices.uv, this.numVertices);
if (vertexHasComponent(VertexFormat.UV1))
Array.Resize(ref this.vertices.uv1, this.numVertices);
if (vertexHasComponent(VertexFormat.UV2))
Array.Resize(ref this.vertices.uv2, this.numVertices);
if (vertexHasComponent(VertexFormat.Tangent))
Array.Resize(ref this.vertices.tangents, this.numVertices);
Array.Resize(ref this.indices, this.numIndices);
}
public bool commit( Mesh mesh )
{
if (isLocked)
return false;
if (this.vertices.positions == null)
return true;
//check mesh null
if (mesh == null)
return false;
mesh.Clear();
// Assign back data
mesh.vertices = this.vertices.positions;
if( vertexHasComponent(VertexFormat.Normal) )
mesh.normals = this.vertices.normals;
if( vertexHasComponent(VertexFormat.BoneWeight) )
mesh.boneWeights = this.vertices.boneWeights;
if( vertexHasComponent(VertexFormat.Color) )
mesh.colors = this.vertices.colors;
if( vertexHasComponent(VertexFormat.UV) )
mesh.uv = this.vertices.uv;
if( vertexHasComponent(VertexFormat.UV1) )
mesh.uv1 = this.vertices.uv1;
if( vertexHasComponent(VertexFormat.UV2) )
mesh.uv2 = this.vertices.uv2;
if( vertexHasComponent(VertexFormat.Tangent) )
mesh.tangents = this.vertices.tangents;
//Debug.Log("Num vertices = " + numVertices);
mesh.triangles = this.indices;
return true;
}
/// <summary>
///
/// </summary>
/// <param name="vertIdx"></param>
/// <param name="indexIdx"></param>
public void reset( int vertIdx, int indexIdx )
{
this.curVertex = vertIdx;
this.curIndex = indexIdx;
MathfEx.Clamp<int>(vertIdx, 0, numVertices);
MathfEx.Clamp<int>(indexIdx, 0, numIndices);
}
public bool isEmpty()
{
return this.vertices.positions == null || this.vertices.positions.Length == 0;
}
public void clear()
{
vertices.positions = null;
vertices.normals = null;
vertices.boneWeights = null;
vertices.colors = null;
vertices.uv = null;
vertices.uv1 = null;
vertices.uv2 = null;
vertices.tangents = null;
indices = null;
numVertices = 0;
numIndices = 0;
firstVertexIndex = 0;
curVertex = 0;
curIndex = 0;
VertFormat = 0;
}
public int CurVertexPos
{
get
{
return curVertex;
}
}
public int CurIndexPos
{
get
{
return curIndex;
}
}
#region Accesing vertex data
public Vector3 Position
{
get {
return this.vertices.positions[curVertex];
}
}
public BoneWeight BoneWeight
{
get {
if( this.vertices.boneWeights == null )
return new BoneWeight();
return this.vertices.boneWeights[curVertex];
}
}
public Vector3 Normal
{
get {
if( this.vertices.normals == null )
return Vector3.zero;
return this.vertices.normals[curVertex];
}
}
public Color Color
{
get {
if( this.vertices.colors == null )
return Color.white;
return this.vertices.colors[curVertex];
}
}
public Vector2 UV
{
get {
if( this.vertices.uv == null )
return Vector2.zero;
return this.vertices.uv[curVertex];
}
}
public Vector2 UV1
{
get {
if( this.vertices.uv1 == null )
return Vector2.zero;
return this.vertices.uv1[curVertex];
}
}
public Vector2 UV2
{
get {
if( this.vertices.uv2 == null )
return Vector2.zero;
return this.vertices.uv2[curVertex];
}
}
public Vector3 Tangent
{
get {
if( this.vertices.tangents == null )
return Vector3.zero;
return this.vertices.tangents[curVertex];
}
}
//-----------------------------------------------------------------------------
// Modifying
//-----------------------------------------------------------------------------
// Position
public void position( float x, float y, float z )
{
if( this.vertices.positions == null ) return;
this.vertices.positions[curVertex].x = x;
this.vertices.positions[curVertex].y = y;
this.vertices.positions[curVertex].z = z;
}
public void position(Vector3 v)
{
if (this.vertices.positions == null) return;
this.vertices.positions[curVertex] = v;
}
//-----------------------------------------------------------------------------
// Bone weights
public void boneWeight( int i, float weight )
{
if( this.vertices.boneWeights == null ) return;
if( i == 0 )
this.vertices.boneWeights[curVertex].weight0 = weight;
else if( i == 1 )
this.vertices.boneWeights[curVertex].weight1 = weight;
else if( i == 2 )
this.vertices.boneWeights[curVertex].weight2 = weight;
else if( i == 3 )
this.vertices.boneWeights[curVertex].weight3 = weight;
}
// Bone weights
public void boneIndex( int i, int boneIndex )
{
if( this.vertices.boneWeights == null ) return;
if( i == 0 )
this.vertices.boneWeights[curVertex].boneIndex0 = boneIndex;
else if( i == 1 )
this.vertices.boneWeights[curVertex].boneIndex1 = boneIndex;
else if( i == 2 )
this.vertices.boneWeights[curVertex].boneIndex2 = boneIndex;
else if( i == 3 )
this.vertices.boneWeights[curVertex].boneIndex3 = boneIndex;
}
//-----------------------------------------------------------------------------
// Normal
public void normal( float nx, float ny, float nz )
{
if( this.vertices.normals == null ) return;
this.vertices.normals[curVertex].x = nx;
this.vertices.normals[curVertex].y = ny;
this.vertices.normals[curVertex].z = nz;
}
public void normal(Vector3 nv)
{
if (this.vertices.normals == null) return;
this.vertices.normals[curVertex] = nv;
}
//-----------------------------------------------------------------------------
// Color float
public void color( float r, float g, float b )
{
if( this.vertices.colors == null ) return;
this.vertices.colors[curVertex].r = r;
this.vertices.colors[curVertex].g = g;
this.vertices.colors[curVertex].b = b;
this.vertices.colors[curVertex].a = 1.0f;
}
public void color( float r, float g, float b, float a )
{
if( this.vertices.colors == null ) return;
this.vertices.colors[curVertex].r = r;
this.vertices.colors[curVertex].g = g;
this.vertices.colors[curVertex].b = b;
this.vertices.colors[curVertex].a = a;
}
//-----------------------------------------------------------------------------
// Color 255
public void color255( byte r, byte g, byte b )
{
if( this.vertices.colors == null ) return;
this.vertices.colors[curVertex].r = r / 255.0f;
this.vertices.colors[curVertex].g = g / 255.0f;
this.vertices.colors[curVertex].b = b / 255.0f;
this.vertices.colors[curVertex].a = 1.0f;
}
public void color255( byte r, byte g, byte b, byte a )
{
if( this.vertices.colors == null ) return;
this.vertices.colors[curVertex].r = r / 255.0f;
this.vertices.colors[curVertex].g = g / 255.0f;
this.vertices.colors[curVertex].b = b / 255.0f;
this.vertices.colors[curVertex].a = a / 255.0f;
}
public void color(GColor c)
{
this.color(c.UnityColor);
}
public void color(Color c)
{
if (this.vertices.colors == null) return;
this.vertices.colors[curVertex] = c;
}
//-----------------------------------------------------------------------------
// UV
public void uv( float u, float v )
{
if( vertices.uv == null ) return;
vertices.uv[curVertex].x = u;
vertices.uv[curVertex].y = v;
}
public void uv(Vector2 v)
{
if (vertices.uv == null) return;
vertices.uv[curVertex] = v;
}
public void uv1( float u, float v )
{
if( vertices.uv1 == null ) return;
vertices.uv1[curVertex].x = u;
vertices.uv1[curVertex].y = v;
}
public void uv1(Vector2 v)
{
if (vertices.uv1 == null) return;
vertices.uv1[curVertex] = v;
}
public void uv2( float u, float v )
{
if( vertices.uv2 == null ) return;
vertices.uv2[curVertex].x = u;
vertices.uv2[curVertex].y = v;
}
public void uv2(Vector2 v)
{
if (vertices.uv2 == null) return;
vertices.uv2[curVertex] = v;
}
//-----------------------------------------------------------------------------
// Tangent
public void tangent( float tx, float ty, float tz )
{
if( vertices.tangents == null ) return;
vertices.tangents[curVertex].x = tx;
vertices.tangents[curVertex].y = ty;
vertices.tangents[curVertex].z = tz;
}
public void tangent(Vector3 tv)
{
if (vertices.tangents == null) return;
vertices.tangents[curVertex] = tv;
}
#endregion
#region Indices
//-----------------------------------------------------------------------------
public int Index
{
get
{
return this.indices[curIndex];
}
set
{
this.indices[curIndex] = this.firstVertexIndex + value;
}
}
public int IndexAuto
{
private get
{
return this.indices[curIndex];
}
set
{
this.indices[curIndex] = this.firstVertexIndex + value;
nextIndex(1);
}
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
public int[] Indices
{
get
{
return (int[]) indices.Clone();
}
set
{
value.CopyTo(this.indices, 0);
curIndex = value.Length;
if (curIndex > numIndices)
curIndex = numIndices;
}
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
public void appendIndices( int[] indices )
{
appendIndices(firstVertexIndex, indices);
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
public void appendIndices( int offset, int[] indices )
{
indices.CopyTo(this.indices, curIndex);
if (offset != 0)
{
for (int i = 0; i < indices.Length; ++i)
this.indices[curIndex + i] += offset;
}
curIndex += indices.Length;
if (curIndex > numIndices)
curIndex = numIndices;
}
/// <summary>
///
/// </summary>
public void generateSequentialIndices()
{
if (indices == null) return;
for (int i = 0; i < numIndices; ++i)
indices[i] = i;
}
#endregion
#region Loop and iteration
public void nextVertex()
{
nextVertex(1);
}
public void nextVertex(int padding)
{
curVertex += padding;
// check boundary (FIXME : out boundary or end of boundary)
if (curVertex >= numVertices)
curVertex = numVertices - 1;
}
public void nextIndex()
{
nextIndex(1);
}
public void nextIndex(int padding)
{
curIndex += padding;
// check boundary (FIXME : out boundary or end of boundary)
if (curIndex >= numIndices)
curIndex = numIndices - 1;
}
public void selectVertex(int idx)
{
curVertex = idx;
if (curVertex >= numVertices)
curVertex = numVertices - 1;
}
public void selectIndex(int idx)
{
curIndex = idx;
if (curIndex >= numIndices)
curIndex = numIndices - 1;
}
#endregion
#region Helpers
public string dumpIndices()
{
string str = String.Format( "[{0}] {{ ", indices.Length );
for (int i = 0; i < indices.Length; i++)
{
str += indices[i] + ", ";
}
str += " }";
return str;
}
//-----------------------------------------------------------------------------
// Compute normals
public bool computeNormals()
{
if ((numIndices <= 0) || (numVertices <= 0))
return false;
if (vertices.normals == null) return false;
// cal num faces
int numFaces = numIndices / 3;
int i, f1, f2, f3;
// Set normal to zero
for (i = 0; i < numVertices; ++i)
vertices.normals[i] = Vector3.zero;
// Calculate normal
Vector3 n, a, b;
for (int iFace = 0; iFace < numFaces; iFace++)
{
i = iFace * 3;
f1 = indices[i];
f2 = indices[i + 1];
f3 = indices[i + 2];
// Get v1, v2, v3 vector
Vector3 v1 = vertices.positions[f1];
Vector3 v2 = vertices.positions[f2];
Vector3 v3 = vertices.positions[f3];
a = new Vector3(v1.x - v1.x, v2.y - v1.y, v2.z - v1.z);
b = new Vector3(v1.x - v3.x, v1.y - v3.y, v1.z - v3.z);
n = Vector3.Cross(a, b);
// accumulate to final normal
vertices.normals[f1] += n;
vertices.normals[f2] += n;
vertices.normals[f2] += n;
}
// Normal lize all normal
for (i = 0; i < numVertices; ++i)
vertices.normals[i].Normalize();
return true;
}
//-----------------------------------------------------------------------------
// Compute tangents
public bool computeTangents()
{
/*if( (numIndices <= 0) || (numVertices <= 0) )
return false;
if( !m_curVertexData.pTangent ||
!m_curVertexData.pBinormal ||
!m_curVertexData.pTexCoord[0] ) return false;
// cal num faces
int numFaces = m_numIndices / 3;
int size = m_meshDesc.vertexStride;
int i, f1, f2, f3;
Vector3_t tangent, binormal, e0, e1;
// check all face
for( int iFace=0; iFace<numFaces; iFace++ )
{
i = iFace * 3;
f1 = m_meshDesc.pIndices[i];
f2 = m_meshDesc.pIndices[i+1];
f3 = m_meshDesc.pIndices[i+2];
// Get v1, v2, v3 texcoord 0
float* pV1 = m_meshDesc.vertexData.pTexCoord[0];
float* pV2 = pV1;
float* pV3 = pV1;
increaseFloatPointer( pV1, size * f1 );
increaseFloatPointer( pV2, size * f2 );
increaseFloatPointer( pV3, size * f3 );
e0.set( 0.0f, pV2[0] - pV1[0], pV2[1] - pV1[1] );
e1.set( 0.0f, pV3[0] - pV1[0], pV3[1] - pV1[1] );
// Get v1, v2, v3 psoition
pV1 = pV2 = pV3 = m_meshDesc.vertexData.pPosition;
increaseFloatPointer( pV1, size * f1 );
increaseFloatPointer( pV2, size * f2 );
increaseFloatPointer( pV3, size * f3 );
for( i=0; i<3; i++ )
{
e0.x = pV2[i] - pV1[i];
e1.x = pV3[i] - pV1[i];
Vector3_t cp;
vec3Cross( &cp, &e0, &e1 );
tangent[i] = -cp.y / cp.x;
binormal[i] = -cp.z / cp.x;
}
vec3Normalize( &tangent, &tangent );
vec3Normalize( &binormal, &binormal );
//vec3Cross( &normal, &tangent, &binormal );
//vec3Cross( &binormal, &normal, &tangent );
// fill tangent
pV1 = pV2 = pV3 = m_meshDesc.vertexData.pTangent;
increaseFloatPointer( pV1, size * f1 );
increaseFloatPointer( pV2, size * f2 );
increaseFloatPointer( pV3, size * f3 );
*((Vector3_t*) pV1) =
*((Vector3_t*) pV2) =
*((Vector3_t*) pV3) = tangent;
// fill binormal
pV1 = pV2 = pV3 = m_meshDesc.vertexData.pBinormal;
increaseFloatPointer( pV1, size * f1 );
increaseFloatPointer( pV2, size * f2 );
increaseFloatPointer( pV3, size * f3 );
*((Vector3_t*) pV1) =
*((Vector3_t*) pV2) =
*((Vector3_t*) pV3) = binormal;
}*/
return true;
}
#endregion
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/MeshBuilder.cs
|
C#
|
asf20
| 20,743
|
using UnityEngine;
using System.Collections;
public class UserProfile : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/UserProfile.cs
|
C#
|
asf20
| 207
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
namespace GFramework
{
/// <summary>
///
/// </summary>
class ConsoleCommandException : Exception
{
public ConsoleCommandException(string Message) : base(Message)
{
}
}
/// <summary>
///
/// </summary>
class ConsoleCommandWrapper
{
public string command = string.Empty;
public ConsoleCommandWrapper(string c)
{
this.command = c;
}
}
/// <summary>
/// Command detail description
/// </summary>
public class CmdDetailAttribute : Attribute
{
public CmdDetailAttribute(string detail)
{
this.Detail = detail;
}
public string Detail { get; private set; }
}
/// <summary>
///
/// </summary>
public class CmdMethodInfo
{
public object instance;
public MethodInfo methodInfo;
public CmdMethodInfo(object instance, MethodInfo methodInfo)
{
this.instance = instance;
this.methodInfo = methodInfo;
}
public string declaration
{
get
{
var builder = new StringBuilder();
ParameterInfo[] parameters = methodInfo.GetParameters();
builder.Append(methodInfo.Name);
if (parameters.Length == 0)
{
builder.Append("()");
}
else
{
builder.Append(" (");
bool flag = true;
foreach (ParameterInfo info in parameters)
{
if (!flag)
{
builder.Append(", ");
}
builder.Append(info.ParameterType.Name + " " + info.Name);
flag = false;
}
builder.Append(")");
}
return builder.ToString();
}
}
/// <summary>
///
/// </summary>
public string briefDescription
{
get
{
var builder = new StringBuilder();
DescriptionAttribute[] customAttributes = (DescriptionAttribute[])methodInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (customAttributes.Length > 0)
{
builder.Append(customAttributes[0].Description);
}
return builder.ToString();
}
}
/// <summary>
///
/// </summary>
public string detailDescription
{
get
{
var builder = new StringBuilder();
CmdDetailAttribute[] detailAttributes = (CmdDetailAttribute[])methodInfo.GetCustomAttributes(typeof(CmdDetailAttribute), false);
if (detailAttributes.Length > 0)
{
builder.Append(detailAttributes[0].Detail);
}
return builder.ToString();
}
}
}
/// <summary>
///
/// </summary>
public class ConsoleCommands
{
/// <summary>
/// Console methods
/// </summary>
public static Dictionary<string, List<CmdMethodInfo>> consoleMethods { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleCommands"/> class.
/// </summary>
static ConsoleCommands()
{
consoleMethods = new Dictionary<string, List<CmdMethodInfo>>();
}
/// <summary>
/// Adds the command provider.
/// </summary>
/// <param name="instance">The instance.</param>
/// <param name="type">The type.</param>
public static void AddCommandProvider(object instance, Type type)
{
if (instance == null && type == null)
return;
BindingFlags bindFlags;
if (instance != null)
{
type = instance.GetType();
bindFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
}
else
{
bindFlags = BindingFlags.Public | BindingFlags.Static;
}
List<string> list = new List<string>();
foreach (MethodInfo info in type.GetMethods(bindFlags))
{
if ((((info.Name != "ToString") && (info.Name != "Equals")) && (info.Name != "GetHashCode")) && (info.Name != "GetType"))
{
foreach (ParameterInfo info2 in info.GetParameters())
{
if (!ConsoleTypeConversion.CanConvertTo(info2.ParameterType))
{
list.Add(info.Name);
}
}
List<CmdMethodInfo> list2 = null;
if (!consoleMethods.TryGetValue(info.Name.ToLower(), out list2))
{
consoleMethods.Add(info.Name.ToLower(), new List<CmdMethodInfo>());
}
consoleMethods[info.Name.ToLower()].Add(new CmdMethodInfo(instance, info));
}
}
if (list.Count > 0)
{
string text = "WARNING!\n\nThe following console methods contain parameters with no supported conversion:\n\n";
foreach (string str2 in list)
{
text = text + str2 + "\n";
}
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
if ((Application.platform == RuntimePlatform.WindowsEditor) || (Application.platform == RuntimePlatform.WindowsPlayer))
{
MessageBox(IntPtr.Zero, text, "Warning", 0);
}
#endif
}
}
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
[DllImport("user32.dll")]
private static extern int MessageBox(IntPtr hWnd, string text, string caption, int type);
#endif
/// <summary>
/// Gets all commands info.
/// </summary>
/// <returns></returns>
public static List<CmdMethodInfo>[] GetAllCommands()
{
StringBuilder builder = new StringBuilder();
List<CmdMethodInfo>[] array = new List<CmdMethodInfo>[consoleMethods.Count];
consoleMethods.Values.CopyTo(array, 0);
Array.Sort<List<CmdMethodInfo>>(array, (l, r) =>
{
if ((l.Count > 0) && (r.Count > 0))
return string.Compare(l[0].methodInfo.Name, r[0].methodInfo.Name);
return 0;
});
return array;
}
/// <summary>
/// Gets the command.
/// </summary>
/// <param name="cmd">The CMD.</param>
/// <returns></returns>
public static List<CmdMethodInfo> GetCommand(string cmd)
{
List<CmdMethodInfo> list = null;
consoleMethods.TryGetValue(cmd.ToLower(), out list);
return list;
}
/// <summary>
/// Gets help for all commands
/// </summary>
/// <returns></returns>
public static string GetAllCommandHelps()
{
List<CmdMethodInfo>[] array = GetAllCommands();
StringBuilder builder = new StringBuilder();
builder.AppendLine("-----------------------------------------------------------------------------------------");
bool isFirst = true;
foreach (List<CmdMethodInfo> list in array)
{
foreach (CmdMethodInfo cmdInfo in list)
{
if (!isFirst)
builder.AppendLine(string.Empty);
else
isFirst = false;
builder.Append("> ");
builder.AppendLine(cmdInfo.declaration);
builder.Append("> ");
builder.AppendLine(cmdInfo.briefDescription);
}
}
builder.AppendLine("-----------------------------------------------------------------------------------------");
return builder.ToString();
}
/// <summary>
/// Gets help for single command
/// </summary>
/// <param name="cmd">The CMD.</param>
/// <returns></returns>
public static string GetCommandHelp(string cmd)
{
List<CmdMethodInfo> list = GetCommand(cmd);
if( list == null )
return "Command \"" + cmd + "\" not found.";
StringBuilder builder = new StringBuilder();
builder.AppendLine("-----------------------------------------------------------------------------------------");
bool isFirst = true;
foreach (CmdMethodInfo cmdInfo in list)
{
if (!isFirst)
builder.AppendLine(string.Empty);
else
isFirst = false;
builder.Append("> ");
builder.AppendLine(cmdInfo.declaration);
builder.Append("> ");
builder.AppendLine(cmdInfo.briefDescription);
string detail = cmdInfo.detailDescription;
if (detail.Length > 0)
{
builder.Append("> ");
builder.AppendLine(cmdInfo.detailDescription);
}
}
builder.AppendLine("-----------------------------------------------------------------------------------------");
return builder.ToString();
}
/// <summary>
/// Executes the specified command.
/// </summary>
/// <param name="Command">The command.</param>
/// <returns></returns>
private static string Execute(string command, object instance, bool excute, out CmdMethodInfo cmdInfo)
{
cmdInfo = null;
string str = string.Empty;
object[] cmdParams = SplitParams(command);
if (cmdParams.Length == 0)
{
return string.Empty;
}
for (int i = 0; i < cmdParams.Length; i++)
{
if (cmdParams[i] is ConsoleCommandWrapper)
{
CmdMethodInfo tmp;
cmdParams[i] = Execute(((ConsoleCommandWrapper)cmdParams[i]).command, instance, true, out tmp);
}
}
if (!(cmdParams[0] is string))
{
throw new ConsoleCommandException("Unknown command \"" + cmdParams[0].ToString() + "\"");
}
string key = ((string)cmdParams[0]).ToLower();
/*if ((key == "help") || (key == "?"))
{
if (cmdParams.Length == 1)
return this.buildHelpString();
if (cmdParams.Length == 2)
return this.buildCommandHelpString((string)cmdParams[1]);
}*/
IList list = null;
List<CmdMethodInfo> list2 = null;
if (consoleMethods.TryGetValue(key, out list2))
{
list = consoleMethods[key];
}
else
{
char[] separator = new char[] { '.' };
string[] strArray = key.Split(separator);
if (strArray.Length == 2)
{
list = FindStaticMethods(strArray[0], strArray[1]);
}
}
if ((list == null) || (list.Count <= 0))
{
throw new ConsoleCommandException("Unknown command \"" + cmdParams[0] + "\"");
}
object[] parameters = null;
foreach(CmdMethodInfo info in list)
{
if (ParametersMatch(info.methodInfo.GetParameters(), cmdParams, out parameters))
{
cmdInfo = info;
if( excute )
return ExecuteCmd(info, instance, parameters);
return "";
}
}
if ((cmdParams.Length > 1) && (cmdParams[1] is object[]))
{
object[] destinationArray = new object[((object[])cmdParams[1]).Length + 1];
destinationArray[0] = cmdParams[0];
Array.Copy((object[])cmdParams[1], 0, destinationArray, 1, ((object[])cmdParams[1]).Length);
foreach(CmdMethodInfo info in list)
{
if (ParametersMatch(info.methodInfo.GetParameters(), destinationArray, out parameters))
{
cmdInfo = info;
if (excute)
return ExecuteCmd(info, instance, parameters);
return "";
}
}
}
str = "Could not find matching parameter list for command \"" + cmdParams[0] + "\" with parameters [";
for (int j = 1; j < cmdParams.Length; j++)
{
if (j > 1)
{
str = str + " ";
}
str = str + cmdParams[j].ToString();
}
throw new ConsoleCommandException(str + "].");
}
/// <summary>
/// Executes the CMD.
/// </summary>
/// <param name="mi">The mi.</param>
/// <param name="Parameters">The parameters.</param>
/// <returns></returns>
private static string ExecuteCmd(CmdMethodInfo mi, object instance, object[] parameters)
{
object obj2 = mi.methodInfo.Invoke(instance != null ? instance : mi.instance, parameters);
return ((obj2 != null) ? obj2.ToString() : string.Empty);
}
/// <summary>
/// Finds the command.
/// </summary>
/// <param name="cmd">The CMD.</param>
/// <param name="instance">The instance.</param>
/// <returns></returns>
public static CmdMethodInfo FindCommand(string cmd, object instance)
{
try
{
CmdMethodInfo result;
Execute(cmd, instance, false, out result);
return result;
}
catch (ConsoleCommandException exception)
{
return null;
}
}
public static CmdMethodInfo FindCommand(string cmd)
{
return FindCommand(cmd, null);
}
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="Cmd">The CMD.</param>
/// <returns></returns>
public static string ExecuteCommand(string cmd, object instance)
{
try
{
CmdMethodInfo info;
return Execute(cmd, instance, true, out info);
}
catch (ConsoleCommandException exception)
{
return ("ERROR: " + exception.Message);
}
}
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="cmd">The CMD.</param>
/// <returns></returns>
public static string ExecuteCommand(string cmd)
{
return ExecuteCommand(cmd, null);
}
/// <summary>
/// Finds the static methods.
/// </summary>
/// <param name="ClassName">Name of the class.</param>
/// <param name="MethodName">Name of the method.</param>
/// <returns></returns>
private static MethodInfo[] FindStaticMethods(string className, string methodName)
{
List<MethodInfo> list = new List<MethodInfo>();
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (System.Type type in assembly.GetTypes())
{
if (string.Compare(type.Name, className, true) == 0)
{
foreach (MethodInfo info in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
{
if (string.Compare(info.Name, methodName, true) == 0)
{
list.Add(info);
}
}
break;
}
}
}
return list.ToArray();
}
/// <summary>
/// Parameterses the match.
/// </summary>
/// <param name="pi">The pi.</param>
/// <param name="CmdParams">The CMD params.</param>
/// <param name="Parameters">The parameters.</param>
/// <returns></returns>
private static bool ParametersMatch(ParameterInfo[] pi, object[] cmdParams, out object[] parameters)
{
parameters = null;
List<object> list = new List<object>();
int cmdParamIndex = 1;
int index = 0;
index = 0;
while (index < pi.Length)
{
object param = null;
if (!ParseParameterType(pi[index].ParameterType, cmdParams, ref cmdParamIndex, out param))
{
break;
}
list.Add(param);
index++;
}
if (index < pi.Length)
{
return false;
}
if (cmdParamIndex < cmdParams.Length)
{
return false;
}
parameters = list.ToArray();
return true;
}
/// <summary>
/// Parses the command parameter.
/// </summary>
/// <param name="Params">The params.</param>
/// <returns></returns>
private static object ParseCommandParameter(ref string parms)
{
parms = parms.Trim();
if (parms[0] == '"')
{
int num = parms.IndexOf('"', 1);
while ((num > 0) && (parms[num - 1] == '\\'))
{
num = parms.IndexOf('"', num + 1);
}
if (num > 0)
{
string str = parms.Substring(1, num - 1);
parms = parms.Substring(num + 1).Trim();
return str.Replace("\\\"", "\"");
}
}
if ((parms[0] == '[') || (parms[0] == '{'))
{
char ch = '[';
char ch2 = ']';
if (parms[0] == '{')
{
ch = '{';
ch2 = '}';
}
int num2 = 1;
int startIndex = 1;
while ((num2 > 0) && (startIndex < parms.Length))
{
if (parms[startIndex] == ch2)
{
num2--;
}
else if (parms[startIndex] == ch)
{
num2++;
}
startIndex++;
}
if (num2 == 0)
{
object obj2 = new ConsoleCommandWrapper(parms.Substring(1, startIndex - 2).Trim());
parms = parms.Substring(startIndex).Trim();
return obj2;
}
}
if (parms[0] == '(')
{
char ch3 = ')';
int num4 = parms.IndexOf(ch3);
if (num4 > 0)
{
string paramString = parms.Substring(1, num4 - 1);
parms = parms.Substring(num4 + 1).Trim();
return SplitParams(paramString);
}
}
string str3 = parms;
int index = parms.IndexOf(' ');
if (index > 0)
{
str3 = parms.Substring(0, index);
parms = parms.Substring(index + 1).Trim();
return str3;
}
parms = string.Empty;
return str3;
}
/// <summary>
/// Parses the type of the parameter.
/// </summary>
/// <param name="ParamType">Type of the param.</param>
/// <param name="CmdParams">The CMD params.</param>
/// <param name="CmdParamIndex">Index of the CMD param.</param>
/// <param name="Param">The param.</param>
/// <returns></returns>
private static bool ParseParameterType(System.Type paramType, object[] cmdParams, ref int cmdParamIndex, out object param)
{
//int num = CmdParamIndex;
bool flag = ConsoleTypeConversion.ConvertToType(cmdParams, ref cmdParamIndex, paramType, out param);
if (!flag)
{
}
return flag;
}
/// <summary>
/// Splits the params.
/// </summary>
/// <param name="ParamString">The param string.</param>
/// <returns></returns>
private static object[] SplitParams(string paramString)
{
paramString = paramString.Trim();
List<object> list = new List<object>();
while (paramString.Length > 0)
{
list.Add(ParseCommandParameter(ref paramString));
}
return list.ToArray();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ConsoleCommands.cs
|
C#
|
asf20
| 17,141
|
//#define LOGIC_TEST // comment for production, uncomment for test sample
using System;
using System.Collections.Generic;
// (c) Gregory Adam 2009
//http://www.brpreiss.com/books/opus4/html/page557.html
/* and
* An Introduction to data structures with applications
* Jean-Paul Tremblay - Paul G. Sorensen
* pages 494-497
*
* Topological sort of a forest of directed acyclic graphs
*
* The algorithm is pretty straight
* for each node, a list of succesors is built
* each node contains its indegree (predecessorCount)
*
* (1) create a queue containing the key of every node that has no predecessors
* (2) while (the queue is not empty)
* dequeue()
* output the key
* remove the key
*
* for each node in the successorList
* decrement its predecessorCount
* if the predecessorCount becomes empty, add it to the queue
*
*
* (3) if any node left, then there is a least one cycle
*
* Sample
* public static bool LogicTest_OK()
* {
* var ts = new TopologicalSort<string>();
* Queue<string> outQueue;
*
* bool returnValue;
*
* ts.Edge("a", "b");
* ts.Edge("a", "c");
*
* ts.Edge("c", "d");
* ts.Edge("c", "e");
*
* returnValue = ts.Sort(out outQueue);
*
* Console.WriteLine(" should get (b d e c a) or (d e c b a)");
*
* while (outQueue.Count != 0)
* Console.WriteLine(" > {0}", outQueue.Dequeue());
*
* Console.WriteLine("Expected true, got {0}, success = {1}",
* returnValue, returnValue);
*
* return returnValue;
* }
*/
// <T> has to implement IEquatable
// <T> cannot be null - since IDictionary is used
/*
* using GregoryAdam.Base.Graph
* var obj = new Graph.TopologicalSort<T>();
*/
/* Methods
*
* public bool Edge(Node)
* returns true or false
*
* public bool Edge(successor, predecessor)
* returns true or false
*
* public bool Sort(out Queue<T> outQueue)
* if true
* returns the evaluation queue
* else
* returns a queue with one cycle
*/
namespace GFramework
{
public sealed class TopologicalSort<T> where T : IEquatable<T>
{
private Dictionary<T, NodeInfo> Nodes = new Dictionary<T, NodeInfo>();
//-------------------------------------------------------------------------
/// <summary>
/// Adds a node with nodeKey
/// Does not complain if the node is already present
/// </summary>
/// <param name="nodeKey"></param>
/// <returns>
/// true on success
/// false if the nodeKey is null
/// </returns>
public bool Edge(T nodeKey)
{
if (nodeKey == null)
return false;
if (!Nodes.ContainsKey(nodeKey))
Nodes.Add(nodeKey, new NodeInfo());
return true;
}
//-------------------------------------------------------------------------
/// <summary>
/// Add an Edge where successor depends on predecessor
/// Does not complain if the directed arc is already in
/// </summary>
/// <param name="successor"></param>
/// <param name="predecessor"></param>
/// <returns>
/// true on success
/// false if either parameter is null
/// or successor equals predecessor
/// </returns>
public bool Edge(T successor, T predecessor)
{
// make sure both nodes are there
if (!Edge(successor)) return false;
if (!Edge(predecessor)) return false;
// if successor == predecessor (cycle) fail
if (successor.Equals(predecessor)) return false;
var successorsOfPredecessor = Nodes[predecessor].Successors;
// if the Edge is already there, keep silent
if (!successorsOfPredecessor.Contains(successor))
{
// add the sucessor to the predecessor's successors
successorsOfPredecessor.Add(successor);
// increment predecessorrCount of successor
Nodes[successor].PredecessorCount++;
}
return true;
}
//-------------------------------------------------------------------------
public bool Sort(out Queue<T> sortedQueue)
{
sortedQueue = new Queue<T>(); // create, even if it stays empty
var outputQueue = new Queue<T>(); // with predecessorCount == 0
// (1) go through all the nodes
// if the node's predecessorCount == 0
// add it to the outputQueue
foreach( KeyValuePair<T, NodeInfo> kvp in Nodes )
if( kvp.Value.PredecessorCount == 0 )
outputQueue.Enqueue(kvp.Key) ;
// (2) process the output Queue
// output the key
// delete the key from Nodes
// foreach successor
// decrement its predecessorCount
// if it becomes zero
// add it to the output Queue
T nodeKey;
NodeInfo nodeInfo;
while (outputQueue.Count != 0)
{
nodeKey = outputQueue.Dequeue();
sortedQueue.Enqueue(nodeKey); // add it to sortedQueue
nodeInfo = Nodes[nodeKey]; // get successors of nodeKey
Nodes.Remove(nodeKey); // remove it from Nodes
foreach (T successor in nodeInfo.Successors)
if (--Nodes[successor].PredecessorCount == 0)
outputQueue.Enqueue(successor);
nodeInfo.Clear();
}
// outputQueue is empty here
if (Nodes.Count == 0)
return true; // if there are no nodes left in Nodes, return true
// there is at least one cycle
CycleInfo(sortedQueue); // get one cycle in sortedQueue
return false; // and fail
}
//-------------------------------------------------------------------------
/// <summary>
/// Clears the Nodes for reuse. Note that Sort() already does this
/// </summary>
public void Clear()
{
foreach (NodeInfo nodeInfo in Nodes.Values)
nodeInfo.Clear();
Nodes.Clear();
}
//-------------------------------------------------------------------------
/// <summary>
/// puts one cycle in cycleQueue
/// </summary>
/// <param name="cycleQueue"></param>
public void CycleInfo(Queue<T> cycleQueue)
{
cycleQueue.Clear(); // Clear the queue, it may have data in it
// init Cycle info of remaining nodes
foreach (NodeInfo nodeInfo in Nodes.Values)
nodeInfo.ContainsCycleKey = nodeInfo.CycleWasOutput = false;
// (1) put the predecessor in the CycleKey of the successor
T cycleKey = default(T);
bool cycleKeyFound = false;
NodeInfo successorInfo;
foreach (KeyValuePair<T, NodeInfo> kvp in Nodes)
{
foreach (T successor in kvp.Value.Successors)
{
successorInfo = Nodes[successor];
if (!successorInfo.ContainsCycleKey)
{
successorInfo.CycleKey = kvp.Key;
successorInfo.ContainsCycleKey = true;
if (!cycleKeyFound)
{
cycleKey = kvp.Key;
cycleKeyFound = true;
}
}
}
kvp.Value.Clear();
}
if( !cycleKeyFound )
throw new Exception("TopologicalSort.CycleInfo: error: !cycleKeyFound");
// (2) put a cycle in cycleQueue
NodeInfo cycleNodeInfo;
while (!(cycleNodeInfo = Nodes[cycleKey]).CycleWasOutput)
{
if (!cycleNodeInfo.ContainsCycleKey)
throw new Exception("TopologicalSort.CycleInfo: error: nodeInfo.ContainsCycleKey");
cycleQueue.Enqueue(cycleKey);
cycleNodeInfo.CycleWasOutput = true;
cycleKey = cycleNodeInfo.CycleKey;
}
}
private class NodeInfo
{
// for construction
public int PredecessorCount;
public List<T> Successors = new List<T>();
// for Cycles in case the sort fails
public T CycleKey;
public bool ContainsCycleKey;
public bool CycleWasOutput;
// Clear NodeInfo
public void Clear()
{
Successors.Clear();
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/TopologicalSort.cs
|
C#
|
asf20
| 7,649
|
using System;
using UnityEngine;
namespace GFramework
{
public class SinCosTable
{
private const int TABLE_SIZE = 3600;
private const float TABLE_CONSTANT = TABLE_SIZE / (2 * Mathf.PI);
private static float[] sinTable;
private static float[] cosTable;
static SinCosTable()
{
Prebuild();
}
public static void Prebuild()
{
if( sinTable == null )
BuildSinTable();
if( cosTable == null )
BuildCosTable();
}
private static void BuildSinTable()
{
// init arrays
sinTable = new float[TABLE_SIZE];
// build lookup tables
float angle = 0;
for (int i = 0; i < TABLE_SIZE; i++)
{
sinTable[i] = Mathf.Sin(angle);
angle += 2 * Mathf.PI / TABLE_SIZE;
}
}
private static void BuildCosTable()
{
// init arrays
cosTable = new float[TABLE_SIZE];
// build lookup tables
float angle = 0;
for (int i = 0; i < TABLE_SIZE; i++)
{
cosTable[i] = Mathf.Cos(angle);
angle += 2 * Mathf.PI / TABLE_SIZE;
}
}
public static float Sin(float radians)
{
int idx = (int)(radians * TABLE_CONSTANT);
idx %= TABLE_SIZE;
if (idx < 0)
idx = TABLE_SIZE + idx;
return sinTable[idx];
}
public static float Cos(float radians)
{
int idx = (int)(radians * TABLE_CONSTANT);
idx %= TABLE_SIZE;
if (idx < 0)
idx = TABLE_SIZE + idx;
return cosTable[idx];
}
}
public class MathfEx
{
public const float PI = Mathf.PI;
public const float HALF_PI = Mathf.PI * 0.5f;
public const float TWO_PI = Mathf.PI * 2f;
public const float DEGREE_PER_PI = 180f / Mathf.PI;
public const float SMALL_NUM = 0.000001f;
public static bool Approx(float val, float about, float range)
{
return (Mathf.Abs((float)(val - about)) < range);
}
public static bool Approx(Vector3 val, Vector3 about, float range)
{
Vector3 vector = val - about;
return (vector.sqrMagnitude < (range * range));
}
public static float Berp(float start, float end, float t)
{
t = Mathf.Clamp01(t);
t = ((Mathf.Sin((t * 3.141593f) * (0.2f + (((2.5f * t) * t) * t))) * Mathf.Pow(1f - t, 2.2f)) + t) * (1f + (1.2f * (1f - t)));
return (start + ((end - start) * t));
}
public static Vector3 Berp(Vector3 start, Vector3 end, float t)
{
float x = Berp(start.x, end.x, t);
float y = Berp(start.y, end.y, t);
return new Vector3(x, y, Berp(start.z, end.z, t));
}
public static float Bounce(float x)
{
return Mathf.Abs((float)(Mathf.Sin((6.28f * (x + 1f)) * (x + 1f)) * (1f - x)));
}
public static T Clamp<T>(T Value, T Min, T Max) where T : IComparable<T>
{
if (Value.CompareTo(Max) > 0)
{
return Max;
}
if (Value.CompareTo(Min) < 0)
{
return Min;
}
return Value;
}
public static float Clerp(float start, float end, float value)
{
float num = 0f;
float num2 = 360f;
float num3 = Mathf.Abs((float)((num2 - num) / 2f));
float num5 = 0f;
if ((end - start) < -num3)
{
num5 = ((num2 - start) + end) * value;
return (start + num5);
}
if ((end - start) > num3)
{
num5 = -((num2 - end) + start) * value;
return (start + num5);
}
return (start + ((end - start) * value));
}
public static float Coserp(float start, float end, float t)
{
return Mathf.Lerp(start, end, 1f - Mathf.Cos((t * 3.141593f) * 0.5f));
}
public static Vector3 Coserp(Vector3 start, Vector3 end, float t)
{
float x = Coserp(start.x, end.x, t);
float y = Coserp(start.y, end.y, t);
return new Vector3(x, y, Coserp(start.z, end.z, t));
}
public static Plane[] GetFrustrumPlanes(ref Matrix4x4 mat)
{
Plane[] planeArray = new Plane[6];
Vector4 v = mat.GetRow(3) + mat.GetRow(0);
planeArray[0] = NormalizedPlaneFromVector(ref v);
v = mat.GetRow(3) - mat.GetRow(0);
planeArray[1] = NormalizedPlaneFromVector(ref v);
v = mat.GetRow(3) + mat.GetRow(1);
planeArray[2] = NormalizedPlaneFromVector(ref v);
v = mat.GetRow(3) - mat.GetRow(1);
planeArray[3] = NormalizedPlaneFromVector(ref v);
v = mat.GetRow(3) + mat.GetRow(2);
planeArray[4] = NormalizedPlaneFromVector(ref v);
v = mat.GetRow(3) - mat.GetRow(2);
planeArray[5] = NormalizedPlaneFromVector(ref v);
return planeArray;
}
public static float Hermite(float start, float end, float t)
{
return Mathf.Lerp(start, end, (t * t) * (3f - (2f * t)));
}
public static Vector3 Hermite(Vector3 start, Vector3 end, float value)
{
float x = Hermite(start.x, end.x, value);
float y = Hermite(start.y, end.y, value);
return new Vector3(x, y, Hermite(start.z, end.z, value));
}
public static float Lerp(float start, float end, float t)
{
return (((1f - t) * start) + (t * end));
}
public static Vector3 NearestPoint(Vector3 lineStart, Vector3 lineEnd, Vector3 point)
{
Vector3 rhs = Vector3.Normalize(lineEnd - lineStart);
float num = Vector3.Dot(point - lineStart, rhs) / Vector3.Dot(rhs, rhs);
return (lineStart + ((Vector3)(num * rhs)));
}
public static Vector3 NearestPointStrict(Vector3 lineStart, Vector3 lineEnd, Vector3 point)
{
Vector3 vector = lineEnd - lineStart;
Vector3 rhs = Vector3.Normalize(vector);
float num = Vector3.Dot(point - lineStart, rhs) / Vector3.Dot(rhs, rhs);
return (lineStart + ((Vector3)(Mathf.Clamp(num, 0f, Vector3.Magnitude(vector)) * rhs)));
}
public static Plane NormalizedPlaneFromVector(ref Vector4 v)
{
float num = 1f / Mathf.Sqrt(((v.x * v.x) + (v.y * v.y)) + (v.z * v.z));
v.x *= num;
v.y *= num;
v.z *= num;
v.w *= num;
return new Plane((Vector3)v, v.w);
}
public static float Sinerp(float start, float end, float t)
{
return Mathf.Lerp(start, end, Mathf.Sin((t * 3.141593f) * 0.5f));
}
public static Vector3 Sinerp(Vector3 start, Vector3 end, float value)
{
float x = Sinerp(start.x, end.x, value);
float y = Sinerp(start.y, end.y, value);
return new Vector3(x, y, Sinerp(start.z, end.z, value));
}
public static Vector3 SmoothDamp(Vector3 current, Vector3 target, ref float currentSpeed, float smoothTime, float maxSpeed, float deltaTime)
{
Vector3 vector = target - current;
float num = Mathf.SmoothDamp(vector.magnitude, 0f, ref currentSpeed, smoothTime, maxSpeed, deltaTime);
return (current + ((Vector3)(vector.normalized * num)));
}
/// <summary>
/// Find angle between 2 vector
/// </summary>
public static float AngleBetweenVectors(Vector2 vector1, Vector2 vector2)
{
float angle = Mathf.Atan2(vector2.y, vector2.x) - Mathf.Atan2(vector1.y, vector1.x);
while (angle > Mathf.PI)
{
angle -= Mathf.PI * 2;
}
while (angle < -Mathf.PI)
{
angle += Mathf.PI * 2;
}
return angle * (180f / Mathf.PI);
}
public static float GetPlanarDistance(Vector3 vector1, Vector3 vector2)
{
return Vector3.Distance(vector1, new Vector3(vector2.x, vector1.y, vector2.z));
}
public static Vector3 GetPlanarDirection(Vector3 position, Vector3 target)
{
Vector3 dir = target - position;
dir.y = 0;
return dir.normalized;
}
public static Vector3 GetForwardVector(Quaternion q)
{
return new Vector3(2 * (q.x * q.z + q.w * q.y),
2 * (q.y * q.x - q.w * q.x),
1 - 2 * (q.x * q.x + q.y * q.y));
}
public static Vector3 GetUpVector(Quaternion q)
{
return new Vector3(2 * (q.x * q.y - q.w * q.z),
1 - 2 * (q.x * q.x + q.z * q.z),
2 * (q.y * q.z + q.w * q.x));
}
public static Vector3 GetRightVector(Quaternion q)
{
return new Vector3(1 - 2 * (q.y * q.y + q.z * q.z),
2 * (q.x * q.y + q.w * q.z),
2 * (q.x * q.z - q.w * q.y));
}
/// <summary>
/// Converts the given decimal number to the numeral system with the
/// specified radix (in the range [2, 36]).
/// </summary>
/// <param name="decimalNumber">The number to convert.</param>
/// <param name="radix">The radix of the destination numeral system
/// (in the range [2, 36]).</param>
/// <returns></returns>
public static string DecimalToArbitrarySystem(long decimalNumber, int radix)
{
const int BitsInLong = 64;
const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (radix < 2 || radix > Digits.Length)
throw new ArgumentException("The radix must be >= 2 and <= " +
Digits.Length.ToString());
if (decimalNumber == 0)
return "0";
int index = BitsInLong - 1;
long currentNumber = Math.Abs(decimalNumber);
char[] charArray = new char[BitsInLong];
while (currentNumber != 0)
{
int remainder = (int)(currentNumber % radix);
charArray[index--] = Digits[remainder];
currentNumber = currentNumber / radix;
}
string result = new String(charArray, index + 1, BitsInLong - index - 1);
if (decimalNumber < 0)
{
result = "-" + result;
}
return result;
}
//Convert number in string representation from base:from to base:to.
//Return result as a string
public static String BaseConvert(int from, int to, String s)
{
//Return error if input is empty
if (String.IsNullOrEmpty(s))
{
return ("Error: Nothing in Input String");
}
//only allow uppercase input characters in string
s = s.ToUpper();
//only do base 2 to base 36 (digit represented by characters 0-Z)"
if (from < 2 || from > 36 || to < 2 || to > 36)
{ return ("Base requested outside range"); }
//convert string to an array of integer digits representing number in base:from
int il = s.Length;
int[] fs = new int[il];
int k = 0;
for (int i = s.Length - 1; i >= 0; i--)
{
if (s[i] >= '0' && s[i] <= '9') { fs[k++] = (int)(s[i] - '0'); }
else
{
if (s[i] >= 'A' && s[i] <= 'Z') { fs[k++] = 10 + (int)(s[i] - 'A'); }
else
{ return ("Error: Input string must only contain any of 0-9 or A-Z"); } //only allow 0-9 A-Z characters
}
}
//check the input for digits that exceed the allowable for base:from
foreach (int i in fs)
{
if (i >= from) { return ("Error: Not a valid number for this input base"); }
}
//find how many digits the output needs
int ol = il * (from / to + 1);
int[] ts = new int[ol + 10]; //assign accumulation array
int[] cums = new int[ol + 10]; //assign the result array
ts[0] = 1; //initialize array with number 1
//evaluate the output
for (int i = 0; i < il; i++) //for each input digit
{
for (int j = 0; j < ol; j++) //add the input digit
// times (base:to from^i) to the output cumulator
{
cums[j] += ts[j] * fs[i];
int temp = cums[j];
int rem = 0;
int ip = j;
do // fix up any remainders in base:to
{
rem = temp / to;
cums[ip] = temp - rem * to; ip++;
cums[ip] += rem;
temp = cums[ip];
}
while (temp >= to);
}
//calculate the next power from^i) in base:to format
for (int j = 0; j < ol; j++)
{
ts[j] = ts[j] * from;
}
for (int j = 0; j < ol; j++) //check for any remainders
{
int temp = ts[j];
int rem = 0;
int ip = j;
do //fix up any remainders
{
rem = temp / to;
ts[ip] = temp - rem * to; ip++;
ts[ip] += rem;
temp = ts[ip];
}
while (temp >= to);
}
}
//convert the output to string format (digits 0,to-1 converted to 0-Z characters)
String sout = String.Empty; //initialize output string
bool first = false; //leading zero flag
for (int i = ol; i >= 0; i--)
{
if (cums[i] != 0) { first = true; }
if (!first) { continue; }
if (cums[i] < 10) { sout += (char)(cums[i] + '0'); }
else { sout += (char)(cums[i] + 'A' - 10); }
}
if (String.IsNullOrEmpty(sout)) { return "0"; } //input was zero, return 0
//return the converted string
return sout;
}
public static bool FasterLineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4)
{
Vector2 a = p2 - p1;
Vector2 b = p3 - p4;
Vector2 c = p1 - p3;
float alphaNumerator = b.y * c.x - b.x * c.y;
float alphaDenominator = a.y * b.x - a.x * b.y;
float betaNumerator = a.x * c.y - a.y * c.x;
float betaDenominator = a.y * b.x - a.x * b.y;
bool doIntersect = true;
if (alphaDenominator == 0 || betaDenominator == 0)
{
doIntersect = false;
}
else
{
if (alphaDenominator > 0)
{
if (alphaNumerator < 0 || alphaNumerator > alphaDenominator)
{
doIntersect = false;
}
}
else if (alphaNumerator > 0 || alphaNumerator < alphaDenominator)
{
doIntersect = false;
}
if (doIntersect && betaDenominator > 0)
{
if (betaNumerator < 0 || betaNumerator > betaDenominator)
{
doIntersect = false;
}
}
else if (betaNumerator > 0 || betaNumerator < betaDenominator)
{
doIntersect = false;
}
}
return doIntersect;
}
public static float SqrDistancePointToSegment(Vector3 point, Vector3 lineP1, Vector3 lineP2, out int closestPoint)
{
Vector3 v = lineP2 - lineP1;
Vector3 w = point - lineP1;
float c1 = Vector3.Dot(w, v);
if (c1 <= 0) //closest point is p1
{
closestPoint = 1;
return Vector3.SqrMagnitude(point - lineP1);
}
float c2 = Vector3.Dot(v, v);
if (c2 <= c1) //closest point is p2
{
closestPoint = 2;
return Vector3.SqrMagnitude(point - lineP2);
}
float b = c1 / c2;
Vector3 pb = lineP1 + b * v;
{
closestPoint = 4;
return Vector3.SqrMagnitude(point - pb);
}
}
public static float SqrDistanceSegmentToSegment(Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out Vector3 closestPt1, out Vector3 closestPt2)
{
Vector3 u = end1 - start1;
Vector3 v = end2 - start2;
Vector3 w = start1 - start2;
float a = Vector3.Dot(u, u); // always >= 0
float b = Vector3.Dot(u, v);
float c = Vector3.Dot(v, v); // always >= 0
float d = Vector3.Dot(u, w);
float e = Vector3.Dot(v, w);
float D = a * c - b * b; // always >= 0
float sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
float tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
// compute the line parameters of the two closest points
if (D < SMALL_NUM)
{ // the lines are almost parallel
sN = 0.0f; // force using point P0 on segment S1
sD = 1.0f; // to prevent possible division by 0.0 later
tN = e;
tD = c;
}
else
{ // get the closest points on the infinite lines
sN = (b * e - c * d);
tN = (a * e - b * d);
if (sN < 0.0)
{ // sc < 0 => the s=0 edge is visible
sN = 0.0f;
tN = e;
tD = c;
}
else if (sN > sD)
{ // sc > 1 => the s=1 edge is visible
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0.0f)
{ // tc < 0 => the t=0 edge is visible
tN = 0.0f;
// recompute sc for this edge
if (-d < 0.0f)
sN = 0.0f;
else if (-d > a)
sN = sD;
else
{
sN = -d;
sD = a;
}
}
else if (tN > tD)
{ // tc > 1 => the t=1 edge is visible
tN = tD;
// recompute sc for this edge
if ((-d + b) < 0.0)
sN = 0;
else if ((-d + b) > a)
sN = sD;
else
{
sN = (-d + b);
sD = a;
}
}
// finally do the division to get sc and tc
sc = (Mathf.Abs(sN) < SMALL_NUM ? 0.0f : sN / sD);
tc = (Mathf.Abs(tN) < SMALL_NUM ? 0.0f : tN / tD);
u *= sc;
v *= tc;
// get the difference of the two closest points
Vector3 dP = w + u - v; // = S1(sc) - S2(tc)
closestPt1 = start1 + u;
closestPt2 = start2 + v;
return dP.sqrMagnitude; // return the closest sqr distance
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/MathfEX.cs
|
C#
|
asf20
| 16,220
|
using UnityEngine;
using System.Collections;
public class GameFPSCounter : MonoBehaviour {
public float frequency = 0.5f;
public int fps;
// Use this for initialization
void Start () {
StartCoroutine(CountFPS());
}
private IEnumerator CountFPS()
{
for (; ; )
{
int lastFrameCount = Time.frameCount;
float lastTime = Time.realtimeSinceStartup;
yield return new WaitForSeconds(frequency);
float timeSpan = Time.realtimeSinceStartup - lastTime;
int frameCount = Time.frameCount - lastFrameCount;
fps = Mathf.RoundToInt(frameCount / timeSpan);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/GameFPSCounter.cs
|
C#
|
asf20
| 606
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace GFramework
{
/// <summary>
/// Generic object manager container
/// Support superior finding on object key and flexible object type-based query
/// </summary>
/// <typeparam name="TKey">Key of the object</typeparam>
/// <typeparam name="TObj">The single object itself</typeparam>
public class ObjectManager<TKey, TObj> where TObj : class
{
#region Fields
protected Dictionary<TKey, TObj> objects = new Dictionary<TKey, TObj>();
protected Dictionary<System.Type, Dictionary<TKey, TObj>> types = new Dictionary<System.Type, Dictionary<TKey, TObj>>();
#endregion
#region Utilities
/// <summary>
/// Return the object count
/// </summary>
public int count
{
get
{
return objects.Count;
}
}
/// <summary>
/// Return the object type count
/// </summary>
public int CountByType(System.Type type)
{
int count = 0;
foreach (var dic in types.Where(p => p.Key == type || p.Key.IsSubclassOf(type)))
{
count += dic.Value.Count;
}
return count;
}
/// <summary>
/// Return the object type count
/// </summary>
public int CountByType<TType>() where TType : TObj
{
int count = 0;
foreach (var dic in types.Where(p => p.Key == typeof(TType) || p.Key.IsSubclassOf(typeof(TType))))
{
count += dic.Value.Count;
}
return count;
}
#endregion
#region Query objects by type
/// <summary>
/// Get all objects of a runtime type
/// </summary>
public IEnumerable<TObj> GetObjectsOfType(System.Type type)
{
return types.
Where(p => p.Key == type || p.Key.IsSubclassOf(type)).
SelectMany(p => p.Value).Select(p => p.Value);
}
/// <summary>
/// Get object of a runtime type
/// </summary>
public TObj GetObjectOfType(System.Type type)
{
return GetObjectsOfType(type).FirstOrDefault();
}
/// <summary>
/// Get all objects of a generic type
/// </summary>
public IEnumerable<TType> GetObjectsOfType<TType>() where TType : TObj
{
return types.
Where(p => p.Key == typeof(TType) || p.Key.IsSubclassOf(typeof(TType))).
SelectMany(p => p.Value).Select(p => (TType) p.Value);
}
/// <summary>
/// Get object of a generic type
/// </summary>
public TType GetObjectOfType<TType>() where TType : TObj
{
return GetObjectsOfType<TType>().FirstOrDefault();
}
/// <summary>
///
/// </summary>
public IEnumerable<TObj> GetAllObjects()
{
return objects.Select(p => p.Value);
}
/// <summary>
///
/// </summary>
public IEnumerable<KeyValuePair<TKey,TObj>> GetAllPairObjects()
{
return objects;
}
#endregion
#region Search objects by criteria
/// <summary>
/// Check if object is valid
/// </summary>
public bool Contains(TKey key)
{
return objects.ContainsKey(key);
}
/// <summary>
/// Find an object by its guid
/// </summary>
public TObj Find(TKey key)
{
TObj result = default(TObj);
objects.TryGetValue(key, out result);
return result;
}
/// <summary>
/// Find an object by its guid
/// </summary>
public TObj Find(TKey key, System.Type objectType)
{
TObj result = default(TObj);
objects.TryGetValue(key, out result);
if (result.GetType() == objectType)
return result;
return null;
}
/// <summary>
/// Find an object by its guid
/// </summary>
public TType Find<TType>(TKey key) where TType : TObj
{
TObj result = default(TObj);
objects.TryGetValue(key, out result);
if (result is TType)
return (TType) result;
return default(TType);
}
/// <summary>
/// Search all objects using predicate criteria
/// </summary>
public IEnumerable<TObj> SearchObjects(Predicate<TObj> criteria)
{
return from p in objects
where criteria(p.Value)
select p.Value;
}
/// <summary>
/// Search an object using predicate criteria
/// </summary>
public TObj SearchObject(Predicate<TObj> criteria)
{
return SearchObjects(criteria).FirstOrDefault();
}
/// <summary>
/// Search all objects using predicate criteria
/// </summary>
public IEnumerable<TType> SearchObjects<TType>(Func<TType, bool> criteria) where TType : TObj
{
return GetObjectsOfType<TType>().Where(o => criteria(o));
}
/// <summary>
/// Search an object using predicate criteria
/// </summary>
public TType SearchObject<TType>(Func<TType, bool> criteria) where TType : TObj
{
return SearchObjects<TType>(criteria).FirstOrDefault();
}
#endregion
#region Instantiate
/// <summary>
/// Instantiate a object with a type name
/// </summary>
public TObj Instantiate(TKey key, string type, object data)
{
TObj obj = (TObj)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(type);
if (!Add(key, obj, data))
return null;
return obj;
}
/// <summary>
/// Instantiate a object with a type and call default constructor
/// </summary>
public TObj Instantiate(TKey key, System.Type type, object data)
{
TObj obj = Activator.CreateInstance(type) as TObj;
if (!Add(key, obj, data))
return null;
return obj;
}
/// <summary>
/// Instantiate a object with a type and call constructor with parameters
/// </summary>
public TObj InstantiateWithParams(TKey key, System.Type type, object[] @param, object data)
{
TObj obj = Activator.CreateInstance(type, @param) as TObj;
if (!Add(key, obj, data))
return null;
return obj;
}
/// <summary>
/// Instantiate a object with factory delegate
/// </summary>
public TObj InstantiateWithCustomCreator(TKey key, Func<TObj> creatorDelegate, object data)
{
TObj obj = creatorDelegate();
if (!Add(key, obj, data))
return null;
return obj;
}
/// <summary>
/// Instantiate a generic object and call default constructor
/// </summary>
public TType Instantiate<TType>(TKey key, object data) where TType : class, TObj, new()
{
TType obj = new TType();
if (!Add(key, obj, data))
return null;
return obj;
}
/// <summary>
/// Instantiate a generic object and call constructor with parameters
/// </summary>
public TType InstantiateWithParams<TType>(TKey key, object[] @param, object data) where TType : class, TObj
{
TType obj = Activator.CreateInstance(typeof(TType), @param) as TType;
if (!Add(key, obj, data))
return null;
return obj;
}
/// <summary>
/// Instantiate a generic object with factory delegate
/// </summary>
public TType InstantiateWithCustomCreator<TType>(TKey key, Func<TType> creatorDelegate, object data) where TType : class, TObj
{
TType obj = creatorDelegate();
if (!Add(key, obj, data))
return null;
return obj;
}
#endregion
#region Add and remove
/// <summary>
/// Add object without pre callback
/// Usage in sub class to call after async call
/// </summary>
public bool AddWithoutCallback(TKey key, TObj obj)
{
// Add to global search list
objects.Add(key, obj);
// Add to type search dictionaries
Dictionary<TKey, TObj> typeObjects;
if (!types.TryGetValue(obj.GetType(), out typeObjects))
{
typeObjects = new Dictionary<TKey, TObj>();
types[obj.GetType()] = typeObjects;
}
// Add the object and notify the callbacks
typeObjects.Add(key, obj);
return true;
}
/// <summary>
/// Add the object
/// </summary>
public bool Add(TKey key, TObj obj)
{
return Add(key, obj, null);
}
/// <summary>
/// Add the object
/// </summary>
public bool Add(TKey key, TObj obj, object data)
{
// Pre add
if (!OnObjectPreAdd(key, obj, data))
return false;
AddWithoutCallback(key, obj);
// Post add
OnObjectPostAdd(key, obj, data);
return true;
}
/// <summary>
/// Add object without pre callback
/// Usage in sub class to call after async call
/// </summary>
public void RemoveWithoutCallback(TKey key)
{
TObj obj = Find(key);
if (obj == null)
return;
// Actual remove
objects.Remove(key);
types[obj.GetType()].Remove(key);
}
/// <summary>
/// Remove the object
/// </summary>
public void Remove(TKey key)
{
TObj obj = Find(key);
if (obj == null)
return;
// Pre remove
OnObjectPreRemove(key, obj);
// Actual remove
objects.Remove(key);
types[obj.GetType()].Remove(key);
// Post remove
OnObjectPostRemove(key, obj);
}
/// <summary>
/// Clear all objects
/// </summary>
public virtual void Clear()
{
TKey[] keys = objects.Keys.ToArray();
// Pre remove
foreach (var key in keys)
Remove(key);
}
#endregion
#region Callbacks
/// <summary>
/// Call before an object about to be added
/// </summary>
/// <returns>return false to abort adding object</returns>
protected virtual bool OnObjectPreAdd(TKey key, TObj obj, object data)
{
return true;
}
/// <summary>
/// Call after an object was added
/// </summary>
protected virtual void OnObjectPostAdd(TKey key, TObj obj, object data)
{
}
/// <summary>
/// Call before an object about to be removed
/// </summary>
/// <returns>return false to abort removing object</returns>
protected virtual void OnObjectPreRemove(TKey key, TObj obj)
{
}
/// <summary>
/// Call after an object was removed
/// </summary>
protected virtual void OnObjectPostRemove(TKey key, TObj obj)
{
}
#endregion
}
public abstract class ObjectManagerSingleton<TThis, TKey, TObj> : ObjectManager<TKey, TObj>
where TThis : ObjectManager<TKey, TObj>, new()
where TObj : class
{
private static readonly TThis singleton = new TThis();
public static TThis instance
{
get
{
return singleton;
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ObjectManager.cs
|
C#
|
asf20
| 10,207
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace GFramework
{
public class Point
{
public float x;
public float y;
}
public static class ConvexHull
{
public static List<Point> FindConvexPolygon(List<Point> points)
{
List<Point> top = new List<Point>();
List<Point> bottom = new List<Point>();
IEnumerable<Point> finalTop;
IEnumerable<Point> finalBottom;
points.Sort((x, y) =>
{
return (int)(x.x - y.x);
});
float deltaX = points.Last().x - points.First().x;
float deltaY = points.Last().y - points.First().y;
float denominator = (Mathf.Pow(deltaX, 2) + Mathf.Pow(deltaY, 2));
for (int i = 1; i < points.Count - 1; i++)
if (MinimumDistanceBetweenPointAndLine2D(points.First(), points.Last(), points[i], deltaX, deltaY, denominator))
bottom.Add(points[i]);
else
top.Add(points[i]);
top.Insert(0, points.First());
top.Add(points.Last());
bottom.Insert(0, points.First());
bottom.Add(points.Last());
finalTop = ConvexHullCore(top, true);
finalBottom = ConvexHullCore(bottom, false);
return finalTop.Union(finalBottom.Reverse()).ToList();
}
private static IEnumerable<Point> ConvexHullCore(List<Point> points, bool isTop)
{
List<Point> result = new List<Point>();
for (int i = 0; i < points.Count; i++)
{
result.Add(points[i]);
if (result.Count > 2 && !IsAngleConvex(result, isTop))
{
result.Remove(result[result.Count - 2]);
result = ConvexHullCore(result, isTop).ToList();
}
}
return result;
}
private static bool IsAngleConvex(List<Point> result, bool isTop)
{
Point lastPoint = result.Last();
Point middlePoint = result[result.Count - 2];
Point firstPoint = result[result.Count - 3];
float firstAngle = Mathf.Atan2(middlePoint.y - firstPoint.y, middlePoint.x - firstPoint.x) * 180.0f / Mathf.PI;
float secondAngle = Mathf.Atan2(lastPoint.y - middlePoint.y, lastPoint.x - middlePoint.x) * 180.0f / Mathf.PI;
return isTop ? secondAngle < firstAngle : secondAngle > firstAngle;
}
private static bool MinimumDistanceBetweenPointAndLine2D(Point P1, Point P2, Point P3, float deltaX, float deltaY, float denominator)
{
float u = ((P3.x - P1.x) * deltaX + (P3.y - P1.y) * deltaY) / denominator;
//float x = P1.X + u * deltaX;
float y = P1.y + u * deltaY;
return y - P3.y > 0;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ConvexHull.cs
|
C#
|
asf20
| 3,069
|
using System;
using System.Reflection;
using UnityEngine;
namespace GFramework
{
/// <summary>
/// Field and Property Info in one single class
/// </summary>
public class FieldPropertyInfo
{
#region Fields
private MemberInfo memberInfo;
#endregion
#region Constructors
private FieldPropertyInfo()
{
}
public FieldPropertyInfo(FieldInfo fieldInfo)
{
this.memberInfo = fieldInfo;
}
public FieldPropertyInfo(PropertyInfo propertyInfo)
{
this.memberInfo = propertyInfo;
}
public FieldPropertyInfo(System.Type type, string fieldPropertyName)
{
this.memberInfo = null;
FieldInfo field = type.GetField(fieldPropertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (field != null)
{
this.memberInfo = field;
}
else
{
PropertyInfo property = type.GetProperty(fieldPropertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (property != null)
{
this.memberInfo = property;
}
}
throw new Exception(string.Concat(new object[] { "FieldPropertyInfo: ", type, ", ", fieldPropertyName }));
}
#endregion //Constructors
#region Public methods
public object GetValue(object obj)
{
return this.GetValue(obj, null);
}
public object GetValue(object obj, object[] index)
{
if (this.memberInfo is FieldInfo)
{
FieldInfo memberInfo = this.memberInfo as FieldInfo;
return memberInfo.GetValue(obj);
}
if (this.memberInfo is PropertyInfo)
{
PropertyInfo propInfo = this.memberInfo as PropertyInfo;
return propInfo.GetValue(obj, index);
}
return null;
}
public bool IsInfoNull()
{
return (this.memberInfo == null);
}
public void SetValue(object obj, object value)
{
this.SetValue(obj, value, null);
}
public void SetValue(object obj, object value, object[] index)
{
if (this.memberInfo is FieldInfo)
{
(this.memberInfo as FieldInfo).SetValue(obj, value);
}
else if (this.memberInfo is PropertyInfo)
{
(this.memberInfo as PropertyInfo).SetValue(obj, value, index);
}
}
public override string ToString()
{
return ((this.memberInfo != null) ? this.memberInfo.ToString() : "");
}
public System.Type FieldPropertyType
{
get
{
if (this.memberInfo is FieldInfo)
{
FieldInfo memberInfo = this.memberInfo as FieldInfo;
return memberInfo.FieldType;
}
if (this.memberInfo is PropertyInfo)
{
PropertyInfo info2 = this.memberInfo as PropertyInfo;
return info2.PropertyType;
}
return null;
}
}
public string Name
{
get
{
return this.memberInfo.Name;
}
}
#endregion
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/FieldPropertyInfo.cs
|
C#
|
asf20
| 3,574
|
using UnityEngine;
using System;
using System.Collections.Generic;
public abstract class SystemModule : GMonoBehaviour
{
/// <summary>
/// Get dependencies
/// </summary>
/// <returns></returns>
public abstract System.Type[] GetDependencies();
/// <summary>
/// Initialize the module
/// </summary>
public abstract void Init();
/// <summary>
/// Shutdown the module
/// </summary>
public abstract void Shutdown();
}
public abstract class SystemModuleSingleton<T> : SystemModule where T : SystemModule
{
private static T singleton;
public static T instance
{
get
{
if (SystemModuleSingleton<T>.singleton == null)
{
SystemModuleSingleton<T>.singleton = (T)FindObjectOfType(typeof(T));
if (SystemModuleSingleton<T>.singleton == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
SystemModuleSingleton<T>.singleton = obj.AddComponent<T>();
}
}
return SystemModuleSingleton<T>.singleton;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/SystemModule.cs
|
C#
|
asf20
| 1,029
|
using UnityEngine;
using System.Linq;
using System.Collections;
/// <summary>
/// Renderer extension.
/// </summary>
public static class RendererExtension
{
public static Material GetManagedMaterial(this Renderer renderer)
{
ManagedMaterial managedMaterial = renderer.GetComponent<ManagedMaterial>();
if (managedMaterial == null)
managedMaterial = renderer.gameObject.AddComponent<ManagedMaterial>();
return managedMaterial.GetMaterial(renderer);
}
public static void SetManagedMaterial(this Renderer renderer, Material material)
{
ManagedMaterial managedMaterial = renderer.GetComponent<ManagedMaterial>();
if (managedMaterial == null)
managedMaterial = renderer.gameObject.AddComponent<ManagedMaterial>();
managedMaterial.SetMaterial(renderer, material);
}
public static Material CreateManagedMaterial(this Renderer renderer, Shader shader)
{
ManagedMaterial managedMaterial = renderer.GetComponent<ManagedMaterial>();
if (managedMaterial == null)
managedMaterial = renderer.gameObject.AddComponent<ManagedMaterial>();
return managedMaterial.CreateMaterial(renderer, shader);
}
public static Material[] GetManagedMaterials(this Renderer renderer)
{
ManagedMaterial managedMaterial = renderer.GetComponent<ManagedMaterial>();
if (managedMaterial == null)
managedMaterial = renderer.gameObject.AddComponent<ManagedMaterial>();
return managedMaterial.GetMaterials(renderer);
}
public static void SetManagedMaterials(this Renderer renderer, Material[] materials)
{
ManagedMaterial managedMaterial = renderer.GetComponent<ManagedMaterial>();
if (managedMaterial == null)
managedMaterial = renderer.gameObject.AddComponent<ManagedMaterial>();
managedMaterial.SetMaterials(renderer, materials);
}
public static Material[] CreateManagedMaterials(this Renderer renderer, int size, Shader shader)
{
ManagedMaterial managedMaterial = renderer.GetComponent<ManagedMaterial>();
if (managedMaterial == null)
managedMaterial = renderer.gameObject.AddComponent<ManagedMaterial>();
return managedMaterial.CreateMaterials(renderer, size, shader);
}
}
/// <summary>
/// Cloned material.
/// </summary>
public class ManagedMaterial : MonoBehaviour
{
private Material[] _materials;
public Material CreateMaterial(Renderer renderer, Shader shader)
{
var mats = CreateMaterials(renderer, 1, shader);
return mats[0];
}
public Material GetMaterial(Renderer renderer)
{
var mats = GetMaterials(renderer);
if (mats != null && mats.Length > 0)
return mats[0];
return null;
}
public void SetMaterial(Renderer renderer, Material material)
{
CleanUp();
renderer.sharedMaterial = material;
}
public Material[] CreateMaterials(Renderer renderer, int size, Shader shader)
{
CleanUp();
_materials = new Material[size];
for (int i = 0; i < size; i++)
{
_materials[i] = new Material(shader);
_materials[i].name = "@" + _materials[i].name;
}
renderer.sharedMaterials = _materials;
return _materials;
}
public Material[] GetMaterials(Renderer renderer)
{
Material[] sharedMaterials = renderer.sharedMaterials;
if (sharedMaterials == null || sharedMaterials.Length == 0)
{
CleanUp();
return null;
}
if (_materials == null)
{
_materials = sharedMaterials.Select(m =>
{
if( m )
{
var mat = new Material(m);
mat.name = "@" + m.name;
return mat;
}
return null;
}).ToArray();
//if (_materials[0].name.StartsWith("@@"))
//Debug.LogError("Dupppppppppppppppppppppp", gameObject);
}
renderer.sharedMaterials = _materials;
return _materials;
}
public void SetMaterials(Renderer renderer, Material[] materials)
{
CleanUp();
renderer.sharedMaterials = materials;
}
void CleanUp()
{
if (_materials != null)
{
foreach (var mat in _materials)
Destroy(mat);
}
_materials = null;
}
void OnDestroy()
{
CleanUp();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ManagedMaterial.cs
|
C#
|
asf20
| 4,329
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using X11;
namespace X11
{
public static partial class Extensions
{
/// <summary>
/// Get property generic
/// </summary>
public static TType GetDataAs<TType>(this Dictionary<short, object> data, short propID)
{
// Get object type
object obj;
if (!data.TryGetValue(propID, out obj))
return default(TType);
return (TType)obj;
}
/// <summary>
/// Get property generic
/// </summary>
public static TType GetDataAs<TType>(this Dictionary<short, object> data, short propID, TType defaultValue)
{
// Get object type
object obj;
if (!data.TryGetValue(propID, out obj))
return defaultValue;
return (TType)obj;
}
/// <summary>
/// Change type of a data
/// </summary>
public static object ChangeType<TThis>(this TThis instance, System.Type toType)
{
if (toType.IsEnum)
return Enum.ToObject(toType, instance);
if (toType.IsArray)
{
System.Type elementType = toType.GetElementType();
if (elementType.IsEnum)
{
IList des = Array.CreateInstance(elementType, ((IList)instance).Count);
for (int i = 0; i < des.Count; i++)
{
des[i] = Enum.ToObject(elementType,((IList)instance)[i]);
}
return Convert.ChangeType(des, toType);
}
}
return Convert.ChangeType(instance, toType);
}
/// <summary>
/// Safe cache and check reference
/// </summary>
public static void SafeReference<TThis>(this TThis instance, Action<TThis> func) where TThis : class
{
if (instance != null)
{
func(instance);
}
}
#region X11 property helpers
/// <summary>
/// Convert a short based disctionary to string base dictionary
/// </summary>
/*public static Dictionary<string, KeyValuePair<short, object>> _prop(this Dictionary<short, object> instance)
{
return instance.ToDictionary(p => p.Key._prop(), p => p);
}
/// <summary>
/// Convert a int ID to propname
/// </summary>
public static string _prop(this int instance)
{
return XProperties.PropName((short)instance);
}
/// <summary>
/// Convert a short ID to propname
/// </summary>
public static string _prop(this short instance)
{
return XProperties.PropName(instance);
}
/// <summary>
/// Convert a prop name to short ID
/// </summary>
public static short _prop(this string instance)
{
return XProperties.PropID(instance);
}*/
#endregion
/*public static bool Any(this IEnumerable source)
{
if (source == null)
{
throw new NullReferenceException("source");
}
using (IEnumerator enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
return true;
}
}
return false;
}*/
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/XExtensions.cs
|
C#
|
asf20
| 2,999
|
using UnityEngine;
using System.Collections;
using System;
using System.Linq;
using System.Collections.Generic;
[ExecuteInEditMode]
public class SkinnedMeshesCombiner : MonoBehaviour
{
/// Usually rendering with triangle strips is faster.
/// However when combining objects with very low triangle counts, it can be faster to use triangles.
/// Best is to try out which value is faster in practice.
public bool castShadows = true;
public bool receiveShadows = true;
// Combine mode
public SkinnedMeshCombinerUtility.CombineMode combineMode = SkinnedMeshCombinerUtility.CombineMode.DuplicateBoneBindpose;
// End combine behaviour
public SkinnedMeshCombinerUtility.EndCombine endCombine = SkinnedMeshCombinerUtility.EndCombine.DestroyChild;
// Filters options
// Name start with filters
public string[] startNameFilters;
// Include inactive
public bool includeInactive;
// Direct children only
public bool directChildOnly;
// Interval to check
public float delay = 0;
public float pollingInterval = 0;
// Rebuild now
public bool rebuildNow = false;
// Current combine group
private Dictionary<SkinnedMeshRenderer, Material[]> currCombinedKey;
// Use this for initialization
void Start()
{
StartCoroutine(PollingCombine());
}
void OnDestroy()
{
SkinnedMeshRenderer thisRenderer = GetComponent<SkinnedMeshRenderer>();
if (thisRenderer != null && thisRenderer.sharedMesh != null)
{
Destroy(thisRenderer.sharedMesh);
thisRenderer.sharedMesh = null;
};
}
public void Combine(bool force)
{
//Getting all Skinned Renderer from Children
SkinnedMeshRenderer[] newCombinedChildren = GetChildSkinnedMeshRenderer();
if (newCombinedChildren.Length > 0)
{
if (force || NeedUpdateCombinedKey(newCombinedChildren))
{
//Debug.Log("******* Rebuild combine skinned mesh - Reason: Sub skinned mesh changed. *******");
// Make sure we have a SkinnedMeshRenderer
SkinnedMeshRenderer thisRenderer = GetComponent<SkinnedMeshRenderer>();
if (thisRenderer == null)
{
thisRenderer = gameObject.AddComponent<SkinnedMeshRenderer>();
thisRenderer.castShadows = castShadows;
thisRenderer.receiveShadows = receiveShadows;
}
SkinnedMeshCombinerUtility combiner = new SkinnedMeshCombinerUtility(combineMode, endCombine, 2000, 64);
if (thisRenderer.sharedMesh != null)
{
Destroy(thisRenderer.sharedMesh);
thisRenderer.sharedMesh = null;
}
combiner.Combine(thisRenderer, newCombinedChildren);
// Update combine key
UpdateCombinedKey(newCombinedChildren);
}
}
else
{
SkinnedMeshRenderer thisRenderer = GetComponent<SkinnedMeshRenderer>();
if (thisRenderer != null)
UnityEngine.Object.Destroy(thisRenderer);
}
}
public IEnumerator PollingCombine()
{
yield return new WaitForSeconds(delay);
do
{
Combine(false);
if (pollingInterval > 0)
yield return new WaitForSeconds(pollingInterval);
}
while (pollingInterval > 0);
}
/// <summary>
/// Determines whether [is skinned mesh renderer the same] [the specified sm renderer1].
/// </summary>
private bool NeedUpdateCombinedKey(SkinnedMeshRenderer[] newSmRenderers)
{
if (currCombinedKey == null)
return true;
if (currCombinedKey.Count != newSmRenderers.Length)
return true;
// Check top level renderer
foreach (var smRenderer in newSmRenderers)
{
if (!currCombinedKey.ContainsKey(smRenderer))
return true;
}
// Check second level renderer material
foreach (var smRenderer in newSmRenderers)
{
if(!smRenderer.sharedMaterials.SequenceEqual(currCombinedKey[smRenderer]))
return true;
}
return false;
/*foreach (var mat in smRenderer1.materials)
{
Debug.LogError("[1]" + smRenderer1.name + " " + mat.name);
}
foreach (var mat in smRenderer2.materials)
{
Debug.LogError("[2]" + smRenderer2.name + " " + mat.name);
}
if (smRenderer1.sharedMaterials.SequenceEqual(smRenderer2.materials))
return true;*/
//Debug.LogError(">>>>>>>> Material is changed");
//return false;
}
/// <summary>
/// Updates the combined key.
/// </summary>
private void UpdateCombinedKey(SkinnedMeshRenderer[] newSmRenderers)
{
if (currCombinedKey == null)
currCombinedKey = new Dictionary<SkinnedMeshRenderer, Material[]>();
currCombinedKey.Clear();
foreach (var smRenderer in newSmRenderers)
{
currCombinedKey.Add(smRenderer, smRenderer.sharedMaterials);
}
}
/// <summary>
/// Gets the child skinned mesh renderer.
/// </summary>
private SkinnedMeshRenderer[] GetChildSkinnedMeshRenderer()
{
SkinnedMeshRenderer[] smRenderers;
if (directChildOnly)
{
smRenderers = transform.Cast<Transform>().Select(t => t.GetComponent<SkinnedMeshRenderer>()).Where(sm => ValidateSkinnedMesh(sm)).ToArray();
}
else
{
smRenderers = GetComponentsInChildren<SkinnedMeshRenderer>(true).Where(sm => ValidateSkinnedMesh(sm)).ToArray();
}
if (startNameFilters == null || startNameFilters.Length == 0)
return smRenderers;
return smRenderers.Where(sm =>
{
if (sm.gameObject == gameObject)
return false;
foreach (var str in startNameFilters)
{
if (sm.name.StartsWith(str))
return true;
}
return false;
}).ToArray();
}
/// <summary>
/// Validates the skinned mesh.
/// </summary>
private bool ValidateSkinnedMesh(SkinnedMeshRenderer smRenderer)
{
if (smRenderer == null || smRenderer.sharedMesh == null)
return false;
if (!includeInactive && smRenderer.gameObject.active == false)
return false;
foreach (var material in smRenderer.sharedMaterials)
{
if (material.mainTexture == null)
return false;
}
return true;
}
#if UNITY_EDITOR
void Update()
{
if (rebuildNow)
{
Combine(true);
rebuildNow = false;
}
}
#endif
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/SkinnedMeshesCombiner.cs
|
C#
|
asf20
| 6,134
|
using UnityEngine;
using System.Collections;
using System;
public class RandomHelper
{
public static readonly System.Random rand = new System.Random();
/// <summary>
/// Roulette selector algorithm
/// </summary>
public static TType SelectRoulette<TType>(TType[] group, Func<TType, float> getFitness)
{
float sumFitness = 0;
for (int i = 0; i < group.Length; i++)
sumFitness += getFitness(group[i]);
bool loop = true;
int idx = -1;
while (loop)
{
float slice = (float)rand.NextDouble() * sumFitness;
float curFitness = 0.0f;
for (int i = 0; i < group.Length; i++)
{
curFitness += getFitness(group[i]);
if (curFitness >= slice )
{
loop = false;
idx = i;
break;
}
}
}
return group[idx];
}
/*public ShuffleBagCollection<float> GetShuffleRandom(ActorStateAnimation[] stateAnims)
{
Dictionary<float, int> weights = new Dictionary<float, int>();
for (int i = 0; i < stateAnimations.Length; i++)
{
weights.Add(i, stateAnimations[i].weight);
}
ShuffleBagCollection<float> shuffleBag = RandomHelper.urand.ShuffleBag(weights);
return shuffleBag;
}*/
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/RandomHelper.cs
|
C#
|
asf20
| 1,187
|
using System;
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return null;
}
private const string fileSizeFormat = "fs";
private const Decimal OneKiloByte = 1024M;
private const Decimal OneMegaByte = OneKiloByte * 1024M;
private const Decimal OneGigaByte = OneMegaByte * 1024M;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (format == null || !format.StartsWith(fileSizeFormat))
{
return defaultFormat(format, arg, formatProvider);
}
if (arg is string)
{
return defaultFormat(format, arg, formatProvider);
}
Decimal size;
try
{
size = Convert.ToDecimal(arg);
}
catch (InvalidCastException)
{
return defaultFormat(format, arg, formatProvider);
}
string suffix;
if (size > OneGigaByte)
{
size /= OneGigaByte;
suffix = " GB";
}
else if (size > OneMegaByte)
{
size /= OneMegaByte;
suffix = " MB";
}
else if (size > OneKiloByte)
{
size /= OneKiloByte;
suffix = " kB";
}
else
{
suffix = " B";
}
string precision = format.Substring(2);
if (String.IsNullOrEmpty(precision)) precision = "2";
return String.Format("{0:N" + precision + "}{1}", size, suffix);
}
private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)
{
IFormattable formattableArg = arg as IFormattable;
if (formattableArg != null)
{
return formattableArg.ToString(format, formatProvider);
}
return arg.ToString();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/FileSizeFormatProvider.cs
|
C#
|
asf20
| 2,103
|
/*
* Copyright (c) 2012 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace MiniJSON {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WHITE_SPACE = " \t\n\r";
const string WORD_BREAK = " \t\n\r{}[],:\"";
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i=0; i< 4; i++) {
hex.Append(NextChar);
}
s.Append((char) Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (WHITE_SPACE.IndexOf(PeekChar) != -1) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (WORD_BREAK.IndexOf(PeekChar) == -1) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
char c = PeekChar;
switch (c) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = NextWord;
switch (word) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
}
else if ((asStr = value as string) != null) {
SerializeString(asStr);
}
else if (value is bool) {
builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null) {
SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
}
else if (value is char) {
SerializeString(value.ToString());
}
else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
}
else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
if (value is float)
builder.Append(value.ToString() + (((float)value % 1 == 0) ? ".0" : ""));
else
if (value is double)
builder.Append(value.ToString() + (((double)value % 1 == 0) ? ".0" : ""));
else
if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal) {
builder.Append(value.ToString());
}
else {
SerializeString(value.ToString());
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/MiniJSON.cs
|
C#
|
asf20
| 18,160
|
using System;
using System.Collections;
using System.Reflection;
using System.Text;
namespace GFramework {
public static class ObjectDumper {
public static string Dump (this object o) {
StringBuilder sb = new StringBuilder();
Dump(sb, o, 0, new ArrayList());
return sb.ToString();
}
private static string Pad (int level, string msg, params object[] args) {
string val = String.Format (msg, args);
return val.PadLeft ((level * 4) + val.Length);
}
private static void Dump (StringBuilder sb, object o, int level, ArrayList previous) {
// Limit level deep
if (level >= 1)
return;
Type type = null;
if (o != null) {
type = o.GetType ();
}
Dump (sb, o, type, null, level, previous);
}
private static void Dump (StringBuilder sb, object o, Type type, string name, int level, ArrayList previous) {
if (o == null) {
sb.AppendLine(Pad(level, "{0} ({1}): (null)", name, type.Name));
return;
}
if (previous.Contains (o)) {
return;
}
previous.Add (o);
if (type.IsPrimitive || o is string) {
DumpPrimitive (sb, o, type, name, level, previous);
} else {
DumpComposite (sb, o, type, name, level, previous);
}
}
private static void DumpPrimitive(StringBuilder sb, object o, Type type, string name, int level, ArrayList previous)
{
if (name != null) {
sb.AppendLine(Pad(level, "{0} ({1}): {2}", name, type.Name, o));
} else {
sb.AppendLine(Pad(level, "({0}) {1}", type.Name, o));
}
}
private static void DumpComposite(StringBuilder sb, object o, Type type, string name, int level, ArrayList previous)
{
if (name != null) {
sb.AppendLine(Pad(level, "{0} ({1}):", name, type.Name));
} else {
sb.AppendLine(Pad(level, "({0})", type.Name));
}
if (o is IDictionary) {
DumpDictionary (sb, (IDictionary) o, level, previous);
} else if (o is ICollection) {
DumpCollection (sb, (ICollection) o, level, previous);
} else {
MemberInfo[] members = o.GetType ().GetMembers (BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic);
foreach (MemberInfo member in members) {
try {
DumpMember (sb, o, member, level, previous);
} catch {}
}
}
}
private static void DumpCollection(StringBuilder sb, ICollection collection, int level, ArrayList previous)
{
foreach (object child in collection) {
Dump (sb, child, level + 1, previous);
}
}
private static void DumpDictionary(StringBuilder sb, IDictionary dictionary, int level, ArrayList previous)
{
foreach (object key in dictionary.Keys) {
sb.AppendLine(Pad(level + 1, "[{0}] ({1}):", key, key.GetType().Name));
Dump (sb, dictionary[key], level + 2, previous);
}
}
private static void DumpMember(StringBuilder sb, object o, MemberInfo member, int level, ArrayList previous)
{
if (member is MethodInfo || member is ConstructorInfo ||
member is EventInfo)
return;
if (member is FieldInfo) {
FieldInfo field = (FieldInfo) member;
string name = member.Name;
if ((field.Attributes & FieldAttributes.Public) == 0) {
name = "#" + name;
}
Dump (sb, field.GetValue (o), field.FieldType, name, level + 1, previous);
} else if (member is PropertyInfo) {
PropertyInfo prop = (PropertyInfo) member;
if (prop.GetIndexParameters ().Length == 0 && prop.CanRead) {
string name = member.Name;
MethodInfo getter = prop.GetGetMethod ();
if ((getter.Attributes & MethodAttributes.Public) == 0) {
name = "#" + name;
}
Dump (sb, prop.GetValue (o, null), prop.PropertyType, name, level + 1, previous);
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ObjectDumper.cs
|
C#
|
asf20
| 4,634
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using UnityEngine;
namespace GFramework
{
public class ConsoleTypeConversion
{
private static Dictionary<System.Type, MethodInfo> methods = new Dictionary<System.Type, MethodInfo>();
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleTypeConversion"/> class.
/// </summary>
static ConsoleTypeConversion()
{
foreach (MethodInfo info in typeof(ConsoleTypeConversion).GetMethods(BindingFlags.NonPublic | BindingFlags.Static))
{
if (info.Name == "convert")
{
ParameterInfo[] parameters = info.GetParameters();
if (parameters.Length == 3)
{
ParameterInfo info2 = parameters[2];
if (info2.ParameterType.IsByRef)
{
methods[info2.ParameterType.GetElementType()] = info;
}
}
}
}
}
/// <summary>
/// Determines whether this instance [can convert to] the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if this instance [can convert to] the specified type; otherwise, <c>false</c>.
/// </returns>
public static bool CanConvertTo(System.Type type)
{
if (type.IsArray)
{
type = type.GetElementType();
}
if (TypeDescriptor.GetConverter(type).CanConvertFrom(typeof(string)))
{
return true;
}
MethodInfo info = null;
return methods.TryGetValue(type, out info);
}
/// <summary>
/// Converts the specified params.
/// </summary>
/// <param name="Params">The params.</param>
/// <param name="ParamIndex">Index of the param.</param>
/// <param name="boolVal">if set to <c>true</c> [bool val].</param>
/// <returns></returns>
private static bool Convert(object[] Params, ref int ParamIndex, out bool boolVal)
{
if ((ParamIndex < Params.Length) && (Params[ParamIndex] is string))
{
if (((string.Compare("1", (string) Params[ParamIndex], true) == 0) || (string.Compare("yes", (string) Params[ParamIndex], true) == 0)) || ((string.Compare("on", (string) Params[ParamIndex], true) == 0) || (string.Compare("true", (string) Params[ParamIndex], true) == 0)))
{
boolVal = true;
ParamIndex++;
return true;
}
if (((string.Compare("0", (string) Params[ParamIndex], true) == 0) || (string.Compare("no", (string) Params[ParamIndex], true) == 0)) || ((string.Compare("off", (string) Params[ParamIndex], true) == 0) || (string.Compare("false", (string) Params[ParamIndex], true) == 0)))
{
boolVal = false;
ParamIndex++;
return true;
}
}
boolVal = false;
return false;
}
/// <summary>
/// Converts the specified params.
/// </summary>
/// <param name="Params">The params.</param>
/// <param name="ParamIndex">Index of the param.</param>
/// <param name="pt">The pt.</param>
/// <returns></returns>
private static bool Convert(object[] Params, ref int ParamIndex, out Vector2 pt)
{
object[] destinationArray = null;
int num = 0;
if (((Params[ParamIndex] is object[]) && (((object[]) Params[ParamIndex]).Length == 2)) && ((((object[]) Params[ParamIndex])[0] is string) && (((object[]) Params[ParamIndex])[1] is string)))
{
destinationArray = (object[]) Params[ParamIndex];
num = 1;
}
else if (((ParamIndex < (Params.Length - 1)) && (Params[ParamIndex] is string)) && (Params[ParamIndex + 1] is string))
{
destinationArray = new object[2];
Array.Copy(Params, ParamIndex, destinationArray, 0, 2);
num = 2;
}
if (destinationArray != null)
{
float x = float.Parse((string) destinationArray[0]);
float y = float.Parse((string) destinationArray[1]);
pt = new Vector2(x, y);
ParamIndex += num;
return true;
}
pt = Vector2.zero;
return false;
}
/// <summary>
/// Converts to type.
/// </summary>
/// <param name="Params">The params.</param>
/// <param name="ParamIndex">Index of the param.</param>
/// <param name="toType">To type.</param>
/// <param name="ConvertedParam">The converted param.</param>
/// <returns></returns>
public static bool ConvertToType(object[] Params, ref int ParamIndex, System.Type toType, out object ConvertedParam)
{
ConvertedParam = null;
if (ParamIndex < Params.Length)
{
if (Params[ParamIndex] is string)
{
bool flag2 = false;
try
{
ConvertedParam = TypeDescriptor.GetConverter(toType).ConvertFromString((string) Params[ParamIndex]);
ParamIndex++;
flag2 = true;
}
catch (Exception)
{
}
return flag2;
}
if (toType.IsArray && (Params[ParamIndex] is object[]))
{
object[] @params = (object[]) Params[ParamIndex];
object[] objArray2 = (object[]) Array.CreateInstance(toType.GetElementType(), @params.Length);
int paramIndex = 0;
while (paramIndex < @params.Length)
{
int index = paramIndex;
object convertedParam = null;
if (!ConvertToType(@params, ref paramIndex, toType.GetElementType(), out convertedParam))
{
break;
}
objArray2[index] = convertedParam;
}
if (paramIndex == @params.Length)
{
ConvertedParam = objArray2;
ParamIndex++;
return true;
}
}
try
{
MethodInfo info = null;
if (methods.TryGetValue(toType, out info))
{
ConvertedParam = null;
object[] parameters = new object[] { Params, (int) ParamIndex, ConvertedParam };
if ((bool) info.Invoke(null, parameters))
{
ParamIndex = (int) parameters[1];
ConvertedParam = parameters[2];
return true;
}
}
}
catch (Exception)
{
}
}
return false;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ConsoleTypeConversion.cs
|
C#
|
asf20
| 7,680
|
using UnityEngine;
using System;
namespace GFramework
{
/// <summary>
/// Color class
/// </summary>
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)]
public struct GColor
{
// access by colorref
[System.Runtime.InteropServices.FieldOffset(0)]
public UInt32 color;
// access by individual element
[System.Runtime.InteropServices.FieldOffset(0)]
public byte b;
[System.Runtime.InteropServices.FieldOffset(1)]
public byte g;
[System.Runtime.InteropServices.FieldOffset(2)]
public byte r;
[System.Runtime.InteropServices.FieldOffset(3)]
public byte a;
/// <summary>
/// Implicit cast to Unity Color
/// </summary>
public static implicit operator UnityEngine.Color(GColor color)
{
return color.UnityColor;
}
/// <summary>
/// Implicit cast to GColor from Unity color
/// </summary>
public static implicit operator GColor(UnityEngine.Color color)
{
return new GColor(color);
}
/// <summary>
/// Implicit cast to GColor from int
/// </summary>
public static implicit operator GColor(UInt32 color)
{
return new GColor(color);
}
//
public GColor( UInt32 cl )
{
a = r = g = b = 0;
color = cl;
}
//
public GColor( byte r, byte g, byte b ) {
color = 0;
this.r = r;
this.g = g;
this.b = b;
this.a = 0xFF;
}
//
public GColor( byte r, byte g, byte b, byte a ) {
color = 0;
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
//
public GColor(UnityEngine.Color cl)
{
color = 0;
a = (byte)(cl.a * 255);
r = (byte)(cl.r * 255);
g = (byte)(cl.g * 255);
b = (byte)(cl.b * 255);
}
//
public static bool operator == (GColor a, GColor b)
{
return a.color == b.color;
}
//
public static bool operator != (GColor a, GColor b)
{
return a.color != b.color;
}
//
public override int GetHashCode()
{
return (int) color;
}
//
public override bool Equals ( object other )
{
return color == ((GColor)other).color;
}
//
void Set(byte r, byte g, byte b)
{
this.r = r;
this.g = g;
this.b = b;
this.a = 0xFF;
}
//
void Set( byte r, byte g, byte b, byte a ) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
//
public UnityEngine.Color UnityColor
{
get
{
return new UnityEngine.Color(r/(float)255, g/(float)255, b/(float)255, a/(float)255);
}
}
public override string ToString()
{
return "_RGBA( " + r + ", " + g + ", " + b + ", " + a + " )";
}
public static readonly GColor AliceBlue = new GColor( 0xFFF0F8FF );
public static readonly GColor AntiqueWhite = new GColor( 0xFFFAEBD7 );
public static readonly GColor Aqua = new GColor( 0xFF00FFFF );
public static readonly GColor Aquamarine = new GColor( 0xFF7FFFD4 );
public static readonly GColor Azure = new GColor( 0xFFF0FFFF );
public static readonly GColor Beige = new GColor( 0xFFF5F5DC );
public static readonly GColor Bisque = new GColor( 0xFFFFE4C4 );
public static readonly GColor Black = new GColor( 0xFF000000 );
public static readonly GColor BlanchedAlmond = new GColor( 0xFFFFEBCD );
public static readonly GColor Blue = new GColor( 0xFF0000FF );
public static readonly GColor BlueViolet = new GColor( 0xFF8A2BE2 );
public static readonly GColor Brown = new GColor( 0xFFA52A2A );
public static readonly GColor BurlyWood = new GColor( 0xFFDEB887 );
public static readonly GColor CadetBlue = new GColor( 0xFF5F9EA0 );
public static readonly GColor Chartreuse = new GColor( 0xFF7FFF00 );
public static readonly GColor Chocolate = new GColor( 0xFFD2691E );
public static readonly GColor Coral = new GColor( 0xFFFF7F50 );
public static readonly GColor CornflowerBlue = new GColor( 0xFF6495ED );
public static readonly GColor Cornsilk = new GColor( 0xFFFFF8DC );
public static readonly GColor Crimson = new GColor( 0xFFDC143C );
public static readonly GColor Cyan = new GColor( 0xFF00FFFF );
public static readonly GColor DarkBlue = new GColor( 0xFF00008B );
public static readonly GColor DarkCyan = new GColor( 0xFF008B8B );
public static readonly GColor DarkGoldenRod = new GColor( 0xFFB8860B );
public static readonly GColor DarkGray = new GColor( 0xFFA9A9A9 );
public static readonly GColor DarkGreen = new GColor( 0xFF006400 );
public static readonly GColor DarkKhaki = new GColor( 0xFFBDB76B );
public static readonly GColor DarkMagenta = new GColor( 0xFF8B008B );
public static readonly GColor DarkOliveGreen = new GColor( 0xFF556B2F );
public static readonly GColor Darkorange = new GColor( 0xFFFF8C00 );
public static readonly GColor DarkOrchid = new GColor( 0xFF9932CC );
public static readonly GColor DarkRed = new GColor( 0xFF8B0000 );
public static readonly GColor DarkSalmon = new GColor( 0xFFE9967A );
public static readonly GColor DarkSeaGreen = new GColor( 0xFF8FBC8F );
public static readonly GColor DarkSlateBlue = new GColor( 0xFF483D8B );
public static readonly GColor DarkSlateGray = new GColor( 0xFF2F4F4F );
public static readonly GColor DarkTurquoise = new GColor( 0xFF00CED1 );
public static readonly GColor DarkViolet = new GColor( 0xFF9400D3 );
public static readonly GColor DeepPink = new GColor( 0xFFFF1493 );
public static readonly GColor DeepSkyBlue = new GColor( 0xFF00BFFF );
public static readonly GColor DimGray = new GColor( 0xFF696969 );
public static readonly GColor DodgerBlue = new GColor( 0xFF1E90FF );
public static readonly GColor FireBrick = new GColor( 0xFFB22222 );
public static readonly GColor FloralWhite = new GColor( 0xFFFFFAF0 );
public static readonly GColor ForestGreen = new GColor( 0xFF228B22 );
public static readonly GColor Fuchsia = new GColor( 0xFFFF00FF );
public static readonly GColor Gainsboro = new GColor( 0xFFDCDCDC );
public static readonly GColor GhostWhite = new GColor( 0xFFF8F8FF );
public static readonly GColor Gold = new GColor( 0xFFFFD700 );
public static readonly GColor GoldenRod = new GColor( 0xFFDAA520 );
public static readonly GColor Gray = new GColor( 0xFF808080 );
public static readonly GColor Green = new GColor( 0xFF008000 );
public static readonly GColor GreenYellow = new GColor( 0xFFADFF2F );
public static readonly GColor HoneyDew = new GColor( 0xFFF0FFF0 );
public static readonly GColor HotPink = new GColor( 0xFFFF69B4 );
public static readonly GColor IndianRed = new GColor( 0xFFCD5C5C );
public static readonly GColor Indigo = new GColor( 0xFF4B0082 );
public static readonly GColor Ivory = new GColor( 0xFFFFFFF0 );
public static readonly GColor Khaki = new GColor( 0xFFF0E68C );
public static readonly GColor Lavender = new GColor( 0xFFE6E6FA );
public static readonly GColor LavenderBlush = new GColor( 0xFFFFF0F5 );
public static readonly GColor LawnGreen = new GColor( 0xFF7CFC00 );
public static readonly GColor LemonChiffon = new GColor( 0xFFFFFACD );
public static readonly GColor LightBlue = new GColor( 0xFFADD8E6 );
public static readonly GColor LightCoral = new GColor( 0xFFF08080 );
public static readonly GColor LightCyan = new GColor( 0xFFE0FFFF );
public static readonly GColor LightGoldenRodYellow = new GColor( 0xFFFAFAD2 );
public static readonly GColor LightGrey = new GColor( 0xFFD3D3D3 );
public static readonly GColor LightGreen = new GColor( 0xFF90EE90 );
public static readonly GColor LightPink = new GColor( 0xFFFFB6C1 );
public static readonly GColor LightSalmon = new GColor( 0xFFFFA07A );
public static readonly GColor LightSeaGreen = new GColor( 0xFF20B2AA );
public static readonly GColor LightSkyBlue = new GColor( 0xFF87CEFA );
public static readonly GColor LightSlateBlue = new GColor( 0xFF8470FF );
public static readonly GColor LightSlateGray = new GColor( 0xFF778899 );
public static readonly GColor LightSteelBlue = new GColor( 0xFFB0C4DE );
public static readonly GColor LightYellow = new GColor( 0xFFFFFFE0 );
public static readonly GColor Lime = new GColor( 0xFF00FF00 );
public static readonly GColor LimeGreen = new GColor( 0xFF32CD32 );
public static readonly GColor Linen = new GColor( 0xFFFAF0E6 );
public static readonly GColor Magenta = new GColor( 0xFFFF00FF );
public static readonly GColor Maroon = new GColor( 0xFF800000 );
public static readonly GColor MediumAquaMarine = new GColor( 0xFF66CDAA );
public static readonly GColor MediumBlue = new GColor( 0xFF0000CD );
public static readonly GColor MediumOrchid = new GColor( 0xFFBA55D3 );
public static readonly GColor MediumPurple = new GColor( 0xFF9370D8 );
public static readonly GColor MediumSeaGreen = new GColor( 0xFF3CB371 );
public static readonly GColor MediumSlateBlue = new GColor( 0xFF7B68EE );
public static readonly GColor MediumSpringGreen = new GColor( 0xFF00FA9A );
public static readonly GColor MediumTurquoise = new GColor( 0xFF48D1CC );
public static readonly GColor MediumVioletRed = new GColor( 0xFFC71585 );
public static readonly GColor MidnightBlue = new GColor( 0xFF191970 );
public static readonly GColor MintCream = new GColor( 0xFFF5FFFA );
public static readonly GColor MistyRose = new GColor( 0xFFFFE4E1 );
public static readonly GColor Moccasin = new GColor( 0xFFFFE4B5 );
public static readonly GColor NavajoWhite = new GColor( 0xFFFFDEAD );
public static readonly GColor Navy = new GColor( 0xFF000080 );
public static readonly GColor OldLace = new GColor( 0xFFFDF5E6 );
public static readonly GColor Olive = new GColor( 0xFF808000 );
public static readonly GColor OliveDrab = new GColor( 0xFF6B8E23 );
public static readonly GColor Orange = new GColor( 0xFFFFA500 );
public static readonly GColor OrangeRed = new GColor( 0xFFFF4500 );
public static readonly GColor Orchid = new GColor( 0xFFDA70D6 );
public static readonly GColor PaleGoldenRod = new GColor( 0xFFEEE8AA );
public static readonly GColor PaleGreen = new GColor( 0xFF98FB98 );
public static readonly GColor PaleTurquoise = new GColor( 0xFFAFEEEE );
public static readonly GColor PaleVioletRed = new GColor( 0xFFD87093 );
public static readonly GColor PapayaWhip = new GColor( 0xFFFFEFD5 );
public static readonly GColor PeachPuff = new GColor( 0xFFFFDAB9 );
public static readonly GColor Peru = new GColor( 0xFFCD853F );
public static readonly GColor Pink = new GColor( 0xFFFFC0CB );
public static readonly GColor Plum = new GColor( 0xFFDDA0DD );
public static readonly GColor PowderBlue = new GColor( 0xFFB0E0E6 );
public static readonly GColor Purple = new GColor( 0xFF800080 );
public static readonly GColor Red = new GColor( 0xFFFF0000 );
public static readonly GColor RosyBrown = new GColor( 0xFFBC8F8F );
public static readonly GColor RoyalBlue = new GColor( 0xFF4169E1 );
public static readonly GColor SaddleBrown = new GColor( 0xFF8B4513 );
public static readonly GColor Salmon = new GColor( 0xFFFA8072 );
public static readonly GColor SandyBrown = new GColor( 0xFFF4A460 );
public static readonly GColor SeaGreen = new GColor( 0xFF2E8B57 );
public static readonly GColor SeaShell = new GColor( 0xFFFFF5EE );
public static readonly GColor Sienna = new GColor( 0xFFA0522D );
public static readonly GColor Silver = new GColor( 0xFFC0C0C0 );
public static readonly GColor SkyBlue = new GColor( 0xFF87CEEB );
public static readonly GColor SlateBlue = new GColor( 0xFF6A5ACD );
public static readonly GColor SlateGray = new GColor( 0xFF708090 );
public static readonly GColor Snow = new GColor( 0xFFFFFAFA );
public static readonly GColor SpringGreen = new GColor( 0xFF00FF7F );
public static readonly GColor SteelBlue = new GColor( 0xFF4682B4 );
public static readonly GColor Tan = new GColor( 0xFFD2B48C );
public static readonly GColor Teal = new GColor( 0xFF008080 );
public static readonly GColor Thistle = new GColor( 0xFFD8BFD8 );
public static readonly GColor Tomato = new GColor( 0xFFFF6347 );
public static readonly GColor Turquoise = new GColor( 0xFF40E0D0 );
public static readonly GColor Violet = new GColor( 0xFFEE82EE );
public static readonly GColor VioletRed = new GColor( 0xFFD02090 );
public static readonly GColor Wheat = new GColor( 0xFFF5DEB3 );
public static readonly GColor White = new GColor( 0xFFFFFFFF );
public static readonly GColor WhiteSmoke = new GColor( 0xFFF5F5F5 );
public static readonly GColor Yellow = new GColor( 0xFFFFFF00 );
public static readonly GColor YellowGreen = new GColor( 0xFF9ACD32 );
public static readonly GColor GrassGreen = new GColor( 0xFF408080 );
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/Color.cs
|
C#
|
asf20
| 12,861
|
using UnityEngine;
using System.Collections;
public class UserProfileManager : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/UserProfileManager.cs
|
C#
|
asf20
| 214
|
using System.Security.Cryptography;
using System;
public class Crc32 : HashAlgorithm
{
public const UInt32 DefaultPolynomial = 0xedb88320;
public const UInt32 DefaultSeed = 0xffffffff;
private UInt32 hash;
private UInt32 seed;
private UInt32[] table;
private static UInt32[] defaultTable;
public Crc32()
{
table = InitializeTable(DefaultPolynomial);
seed = DefaultSeed;
Initialize();
}
public Crc32(UInt32 polynomial, UInt32 seed)
{
table = InitializeTable(polynomial);
this.seed = seed;
Initialize();
}
public override void Initialize()
{
hash = seed;
}
protected override void HashCore(byte[] buffer, int start, int length)
{
hash = CalculateHash(table, hash, buffer, start, length);
}
protected override byte[] HashFinal()
{
byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
this.HashValue = hashBuffer;
return hashBuffer;
}
public override int HashSize
{
get { return 32; }
}
public static UInt32 Compute(byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
}
public static UInt32 Compute(UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
}
public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
}
private static UInt32[] InitializeTable(UInt32 polynomial)
{
if (polynomial == DefaultPolynomial && defaultTable != null)
return defaultTable;
UInt32[] createTable = new UInt32[256];
for (int i = 0; i < 256; i++)
{
UInt32 entry = (UInt32)i;
for (int j = 0; j < 8; j++)
if ((entry & 1) == 1)
entry = (entry >> 1) ^ polynomial;
else
entry = entry >> 1;
createTable[i] = entry;
}
if (polynomial == DefaultPolynomial)
defaultTable = createTable;
return createTable;
}
private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size)
{
UInt32 crc = seed;
for (int i = start; i < size; i++)
unchecked
{
crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
}
return crc;
}
private byte[] UInt32ToBigEndianBytes(UInt32 x)
{
return new byte[] {
(byte)((x >> 24) & 0xff),
(byte)((x >> 16) & 0xff),
(byte)((x >> 8) & 0xff),
(byte)(x & 0xff)
};
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/CRC32.cs
|
C#
|
asf20
| 2,490
|
using System.Collections;
using System;
using UnityEngine;
/* Perlin noise use example:
Perlin perlin = new Perlin();
var value : float = perlin.Noise(2);
var value : float = perlin.Noise(2, 3, );
var value : float = perlin.Noise(2, 3, 4);
SmoothRandom use example:
var p = SmoothRandom.GetVector3(3);
*/
public class SmoothRandom
{
public static Vector3 GetVector3 (float speed)
{
float time = Time.time * 0.01F * speed;
return new Vector3(Get().HybridMultifractal(time, 15.73F, 0.58F), Get().HybridMultifractal(time, 63.94F, 0.58F), Get().HybridMultifractal(time, 0.2F, 0.58F));
}
public static float Get (float speed)
{
float time = Time.time * 0.01F * speed;
return Get().HybridMultifractal(time * 0.01F, 15.7F, 0.65F);
}
private static FractalNoise Get () {
if (s_Noise == null)
s_Noise = new FractalNoise (1.27F, 2.04F, 8.36F);
return s_Noise;
}
private static FractalNoise s_Noise;
}
public class Perlin
{
// Original C code derived from
// http://astronomy.swin.edu.au/~pbourke/texture/perlin/perlin.c
// http://astronomy.swin.edu.au/~pbourke/texture/perlin/perlin.h
const int B = 0x100;
const int BM = 0xff;
const int N = 0x1000;
int[] p = new int[B + B + 2];
float[,] g3 = new float [B + B + 2 , 3];
float[,] g2 = new float[B + B + 2,2];
float[] g1 = new float[B + B + 2];
float s_curve(float t)
{
return t * t * (3.0F - 2.0F * t);
}
float lerp (float t, float a, float b)
{
return a + t * (b - a);
}
void setup (float value, out int b0, out int b1, out float r0, out float r1)
{
float t = value + N;
b0 = ((int)t) & BM;
b1 = (b0+1) & BM;
r0 = t - (int)t;
r1 = r0 - 1.0F;
}
float at2(float rx, float ry, float x, float y) { return rx * x + ry * y; }
float at3(float rx, float ry, float rz, float x, float y, float z) { return rx * x + ry * y + rz * z; }
public float Noise(float arg)
{
int bx0, bx1;
float rx0, rx1, sx, u, v;
setup(arg, out bx0, out bx1, out rx0, out rx1);
sx = s_curve(rx0);
u = rx0 * g1[ p[ bx0 ] ];
v = rx1 * g1[ p[ bx1 ] ];
return(lerp(sx, u, v));
}
public float Noise(float x, float y)
{
int bx0, bx1, by0, by1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, sx, sy, a, b, u, v;
int i, j;
setup(x, out bx0, out bx1, out rx0, out rx1);
setup(y, out by0, out by1, out ry0, out ry1);
i = p[ bx0 ];
j = p[ bx1 ];
b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];
sx = s_curve(rx0);
sy = s_curve(ry0);
u = at2(rx0,ry0, g2[ b00, 0 ], g2[ b00, 1 ]);
v = at2(rx1,ry0, g2[ b10, 0 ], g2[ b10, 1 ]);
a = lerp(sx, u, v);
u = at2(rx0,ry1, g2[ b01, 0 ], g2[ b01, 1 ]);
v = at2(rx1,ry1, g2[ b11, 0 ], g2[ b11, 1 ]);
b = lerp(sx, u, v);
return lerp(sy, a, b);
}
public float Noise(float x, float y, float z)
{
int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, rz0, rz1, sy, sz, a, b, c, d, t, u, v;
int i, j;
setup(x, out bx0, out bx1, out rx0, out rx1);
setup(y, out by0, out by1, out ry0, out ry1);
setup(z, out bz0, out bz1, out rz0, out rz1);
i = p[ bx0 ];
j = p[ bx1 ];
b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];
t = s_curve(rx0);
sy = s_curve(ry0);
sz = s_curve(rz0);
u = at3(rx0,ry0,rz0, g3[ b00 + bz0, 0 ], g3[ b00 + bz0, 1 ], g3[ b00 + bz0, 2 ]);
v = at3(rx1,ry0,rz0, g3[ b10 + bz0, 0 ], g3[ b10 + bz0, 1 ], g3[ b10 + bz0, 2 ]);
a = lerp(t, u, v);
u = at3(rx0,ry1,rz0, g3[ b01 + bz0, 0 ], g3[ b01 + bz0, 1 ], g3[ b01 + bz0, 2 ]);
v = at3(rx1,ry1,rz0, g3[ b11 + bz0, 0 ], g3[ b11 + bz0, 1 ], g3[ b11 + bz0, 2 ]);
b = lerp(t, u, v);
c = lerp(sy, a, b);
u = at3(rx0,ry0,rz1, g3[ b00 + bz1, 0 ], g3[ b00 + bz1, 2 ], g3[ b00 + bz1, 2 ]);
v = at3(rx1,ry0,rz1, g3[ b10 + bz1, 0 ], g3[ b10 + bz1, 1 ], g3[ b10 + bz1, 2 ]);
a = lerp(t, u, v);
u = at3(rx0,ry1,rz1, g3[ b01 + bz1, 0 ], g3[ b01 + bz1, 1 ], g3[ b01 + bz1, 2 ]);
v = at3(rx1,ry1,rz1,g3[ b11 + bz1, 0 ], g3[ b11 + bz1, 1 ], g3[ b11 + bz1, 2 ]);
b = lerp(t, u, v);
d = lerp(sy, a, b);
return lerp(sz, c, d);
}
void normalize2(ref float x, ref float y)
{
float s;
s = (float)Math.Sqrt(x * x + y * y);
x = y / s;
y = y / s;
}
void normalize3(ref float x, ref float y, ref float z)
{
float s;
s = (float)Math.Sqrt(x * x + y * y + z * z);
x = y / s;
y = y / s;
z = z / s;
}
public Perlin()
{
int i, j, k;
System.Random rnd = new System.Random();
for (i = 0 ; i < B ; i++) {
p[i] = i;
g1[i] = (float)(rnd.Next(B + B) - B) / B;
for (j = 0 ; j < 2 ; j++)
g2[i,j] = (float)(rnd.Next(B + B) - B) / B;
normalize2(ref g2[i, 0], ref g2[i, 1]);
for (j = 0 ; j < 3 ; j++)
g3[i,j] = (float)(rnd.Next(B + B) - B) / B;
normalize3(ref g3[i, 0], ref g3[i, 1], ref g3[i, 2]);
}
while (--i != 0) {
k = p[i];
p[i] = p[j = rnd.Next(B)];
p[j] = k;
}
for (i = 0 ; i < B + 2 ; i++) {
p[B + i] = p[i];
g1[B + i] = g1[i];
for (j = 0 ; j < 2 ; j++)
g2[B + i,j] = g2[i,j];
for (j = 0 ; j < 3 ; j++)
g3[B + i,j] = g3[i,j];
}
}
}
public class FractalNoise
{
public FractalNoise (float inH, float inLacunarity, float inOctaves)
: this (inH, inLacunarity, inOctaves, null)
{
}
public FractalNoise (float inH, float inLacunarity, float inOctaves, Perlin noise)
{
m_Lacunarity = inLacunarity;
m_Octaves = inOctaves;
m_IntOctaves = (int)inOctaves;
m_Exponent = new float[m_IntOctaves+1];
float frequency = 1.0F;
for (int i = 0; i < m_IntOctaves+1; i++)
{
m_Exponent[i] = (float)Math.Pow (m_Lacunarity, -inH);
frequency *= m_Lacunarity;
}
if (noise == null)
m_Noise = new Perlin();
else
m_Noise = noise;
}
public float HybridMultifractal(float x, float y, float offset)
{
float weight, signal, remainder, result;
result = (m_Noise.Noise (x, y)+offset) * m_Exponent[0];
weight = result;
x *= m_Lacunarity;
y *= m_Lacunarity;
int i;
for (i=1;i<m_IntOctaves;i++)
{
if (weight > 1.0F) weight = 1.0F;
signal = (m_Noise.Noise (x, y) + offset) * m_Exponent[i];
result += weight * signal;
weight *= signal;
x *= m_Lacunarity;
y *= m_Lacunarity;
}
remainder = m_Octaves - m_IntOctaves;
result += remainder * m_Noise.Noise (x,y) * m_Exponent[i];
return result;
}
public float RidgedMultifractal (float x, float y, float offset, float gain)
{
float weight, signal, result;
int i;
signal = Mathf.Abs (m_Noise.Noise (x, y));
signal = offset - signal;
signal *= signal;
result = signal;
weight = 1.0F;
for (i=1;i<m_IntOctaves;i++)
{
x *= m_Lacunarity;
y *= m_Lacunarity;
weight = signal * gain;
weight = Mathf.Clamp01 (weight);
signal = Mathf.Abs (m_Noise.Noise (x, y));
signal = offset - signal;
signal *= signal;
signal *= weight;
result += signal * m_Exponent[i];
}
return result;
}
public float BrownianMotion (float x, float y)
{
float value, remainder;
long i;
value = 0.0F;
for (i=0;i<m_IntOctaves;i++)
{
value = m_Noise.Noise (x,y) * m_Exponent[i];
x *= m_Lacunarity;
y *= m_Lacunarity;
}
remainder = m_Octaves - m_IntOctaves;
value += remainder * m_Noise.Noise (x,y) * m_Exponent[i];
return value;
}
private Perlin m_Noise;
private float[] m_Exponent;
private int m_IntOctaves;
private float m_Octaves;
private float m_Lacunarity;
}
/*
/// This is an alternative implementation of perlin noise
public class Noise
{
public float Noise(float x)
{
return Noise(x, 0.5F);
}
public float Noise(float x, float y)
{
int Xint = (int)x;
int Yint = (int)y;
float Xfrac = x - Xint;
float Yfrac = y - Yint;
float x0y0 = Smooth_Noise(Xint, Yint); //find the noise values of the four corners
float x1y0 = Smooth_Noise(Xint+1, Yint);
float x0y1 = Smooth_Noise(Xint, Yint+1);
float x1y1 = Smooth_Noise(Xint+1, Yint+1);
//interpolate between those values according to the x and y fractions
float v1 = Interpolate(x0y0, x1y0, Xfrac); //interpolate in x direction (y)
float v2 = Interpolate(x0y1, x1y1, Xfrac); //interpolate in x direction (y+1)
float fin = Interpolate(v1, v2, Yfrac); //interpolate in y direction
return fin;
}
private float Interpolate(float x, float y, float a)
{
float b = 1-a;
float fac1 = (float)(3*b*b - 2*b*b*b);
float fac2 = (float)(3*a*a - 2*a*a*a);
return x*fac1 + y*fac2; //add the weighted factors
}
private float GetRandomValue(int x, int y)
{
x = (x+m_nNoiseWidth) % m_nNoiseWidth;
y = (y+m_nNoiseHeight) % m_nNoiseHeight;
float fVal = (float)m_aNoise[(int)(m_fScaleX*x), (int)(m_fScaleY*y)];
return fVal/255*2-1f;
}
private float Smooth_Noise(int x, int y)
{
float corners = ( Noise2d(x-1, y-1) + Noise2d(x+1, y-1) + Noise2d(x-1, y+1) + Noise2d(x+1, y+1) ) / 16.0f;
float sides = ( Noise2d(x-1, y) +Noise2d(x+1, y) + Noise2d(x, y-1) + Noise2d(x, y+1) ) / 8.0f;
float center = Noise2d(x, y) / 4.0f;
return corners + sides + center;
}
private float Noise2d(int x, int y)
{
x = (x+m_nNoiseWidth) % m_nNoiseWidth;
y = (y+m_nNoiseHeight) % m_nNoiseHeight;
float fVal = (float)m_aNoise[(int)(m_fScaleX*x), (int)(m_fScaleY*y)];
return fVal/255*2-1f;
}
public Noise()
{
m_nNoiseWidth = 100;
m_nNoiseHeight = 100;
m_fScaleX = 1.0F;
m_fScaleY = 1.0F;
System.Random rnd = new System.Random();
m_aNoise = new int[m_nNoiseWidth,m_nNoiseHeight];
for (int x = 0; x<m_nNoiseWidth; x++)
{
for (int y = 0; y<m_nNoiseHeight; y++)
{
m_aNoise[x,y] = rnd.Next(255);
}
}
}
private int[,] m_aNoise;
protected int m_nNoiseWidth, m_nNoiseHeight;
private float m_fScaleX, m_fScaleY;
}
/* Yet another perlin noise implementation. This one is not even completely ported to C#
float noise1[];
float noise2[];
float noise3[];
int indices[];
float PerlinSmoothStep (float t)
{
return t * t * (3.0f - 2.0f * t);
}
float PerlinLerp(float t, float a, float b)
{
return a + t * (b - a);
}
float PerlinRand()
{
return Random.rand () / float(RAND_MAX) * 2.0f - 1.0f;
}
PerlinNoise::PerlinNoise ()
{
long i, j, k;
float x, y, z, denom;
Random rnd = new Random();
noise1 = new float[1 * (PERLIN_B + PERLIN_B + 2)];
noise2 = new float[2 * (PERLIN_B + PERLIN_B + 2)];
noise3 = new float[3 * (PERLIN_B + PERLIN_B + 2)];
indices = new long[PERLIN_B + PERLIN_B + 2];
for (i = 0; i < PERLIN_B; i++)
{
indices[i] = i;
x = PerlinRand();
y = PerlinRand();
z = PerlinRand();
noise1[i] = x;
denom = sqrt(x * x + y * y);
if (denom > 0.0001f) denom = 1.0f / denom;
j = i << 1;
noise2[j + 0] = x * denom;
noise2[j + 1] = y * denom;
denom = sqrt(x * x + y * y + z * z);
if (denom > 0.0001f) denom = 1.0f / denom;
j += i;
noise3[j + 0] = x * denom;
noise3[j + 1] = y * denom;
noise3[j + 2] = z * denom;
}
while (--i != 0)
{
j = rand() & PERLIN_BITMASK;
std::swap (indices[i], indices[j]);
}
for (i = 0; i < PERLIN_B + 2; i++)
{
j = i + PERLIN_B;
indices[j] = indices[i];
noise1[j] = noise1[i];
j = j << 1;
k = i << 1;
noise2[j + 0] = noise2[k + 0];
noise2[j + 1] = noise2[k + 1];
j += i + PERLIN_B;
k += i + PERLIN_B;
noise3[j + 0] = noise3[k + 0];
noise3[j + 1] = noise3[k + 1];
noise3[j + 2] = noise3[k + 2];
}
}
PerlinNoise::~PerlinNoise ()
{
delete []noise1;
delete []noise2;
delete []noise3;
delete []indices;
}
void PerlinSetup (float v, long& b0, long& b1, float& r0, float& r1);
void PerlinSetup(
float v,
long& b0,
long& b1,
float& r0,
float& r1)
{
v += PERLIN_N;
long vInt = (long)v;
b0 = vInt & PERLIN_BITMASK;
b1 = (b0 + 1) & PERLIN_BITMASK;
r0 = v - (float)vInt;
r1 = r0 - 1.0f;
}
float PerlinNoise::Noise1 (float x)
{
long bx0, bx1;
float rx0, rx1, sx, u, v;
PerlinSetup(x, bx0, bx1, rx0, rx1);
sx = PerlinSmoothStep(rx0);
u = rx0 * noise1[indices[bx0]];
v = rx1 * noise1[indices[bx1]];
return PerlinLerp (sx, u, v);
}
float PerlinNoise::Noise2(float x, float y)
{
long bx0, bx1, by0, by1, b00, b01, b10, b11;
float rx0, rx1, ry0, ry1, sx, sy, u, v, a, b;
PerlinSetup (x, bx0, bx1, rx0, rx1);
PerlinSetup (y, by0, by1, ry0, ry1);
sx = PerlinSmoothStep (rx0);
sy = PerlinSmoothStep (ry0);
b00 = indices[indices[bx0] + by0] << 1;
b10 = indices[indices[bx1] + by0] << 1;
b01 = indices[indices[bx0] + by1] << 1;
b11 = indices[indices[bx1] + by1] << 1;
u = rx0 * noise2[b00 + 0] + ry0 * noise2[b00 + 1];
v = rx1 * noise2[b10 + 0] + ry0 * noise2[b10 + 1];
a = PerlinLerp (sx, u, v);
u = rx0 * noise2[b01 + 0] + ry1 * noise2[b01 + 1];
v = rx1 * noise2[b11 + 0] + ry1 * noise2[b11 + 1];
b = PerlinLerp (sx, u, v);
u = PerlinLerp (sy, a, b);
return u;
}
float PerlinNoise::Noise3(float x, float y, float z)
{
long bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
PerlinSetup (x, bx0, bx1, rx0, rx1);
PerlinSetup (y, by0, by1, ry0, ry1);
PerlinSetup (z, bz0, bz1, rz0, rz1);
b00 = indices[indices[bx0] + by0] << 1;
b10 = indices[indices[bx1] + by0] << 1;
b01 = indices[indices[bx0] + by1] << 1;
b11 = indices[indices[bx1] + by1] << 1;
t = PerlinSmoothStep (rx0);
sy = PerlinSmoothStep (ry0);
sz = PerlinSmoothStep (rz0);
#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] )
q = &noise3[b00 + bz0]; u = at3(rx0,ry0,rz0);
q = &noise3[b10 + bz0]; v = at3(rx1,ry0,rz0);
a = PerlinLerp(t, u, v);
q = &noise3[b01 + bz0]; u = at3(rx0,ry1,rz0);
q = &noise3[b11 + bz0]; v = at3(rx1,ry1,rz0);
b = PerlinLerp(t, u, v);
c = PerlinLerp(sy, a, b);
q = &noise3[b00 + bz1]; u = at3(rx0,ry0,rz1);
q = &noise3[b10 + bz1]; v = at3(rx1,ry0,rz1);
a = PerlinLerp(t, u, v);
q = &noise3[b01 + bz1]; u = at3(rx0,ry1,rz1);
q = &noise3[b11 + bz1]; v = at3(rx1,ry1,rz1);
b = PerlinLerp(t, u, v);
d = PerlinLerp(sy, a, b);
return PerlinLerp (sz, c, d);
}
*/
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/Perlin.cs
|
C#
|
asf20
| 14,232
|
using UnityEngine;
using System;
/// <summary>
/// Singleton base class
/// </summary>
public class Singleton<T> where T : class, new()
{
private static readonly T singleton = new T();
public static T instance
{
get
{
return singleton;
}
}
}
/// <summary>
/// Singleton for mono behavior object
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T singleton;
public static bool IsInstanceValid() { return singleton != null; }
void Reset()
{
gameObject.name = typeof(T).Name;
}
public static T instance
{
get
{
if (SingletonMono<T>.singleton == null)
{
SingletonMono<T>.singleton = (T)FindObjectOfType(typeof(T));
if (SingletonMono<T>.singleton == null)
{
GameObject obj = new GameObject();
obj.name = "[@" + typeof(T).Name + "]";
SingletonMono<T>.singleton = obj.AddComponent<T>();
}
}
return SingletonMono<T>.singleton;
}
}
}
/// <summary>
/// Singleton for mono behavior object
/// </summary>
/// <typeparam name="T"></typeparam>
public class ManualSingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
public static T instance { get; private set; }
void Reset()
{
gameObject.name = typeof(T).Name;
}
protected virtual void Awake()
{
if (instance == null)
instance = (T)(MonoBehaviour)this;
}
protected void OnDestroy()
{
if (instance == this)
instance = null;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/Singleton.cs
|
C#
|
asf20
| 1,734
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using X11;
using GFramework;
namespace X11
{
public static partial class Extensions
{
#region Unity type helpers
/// <summary>
/// Check vector equals
/// </summary>
public static bool EqualsEpsilon(this float[] l, float[] r, float epsilon)
{
if (l == null || r == null)
return l == r;
if (l.Length != r.Length)
return false;
for (int i = 0; i < l.Length; i++)
{
if (!MathfEx.Approx(l[i], r[i], epsilon))
return false;
}
return true;
}
/// <summary>
/// Check vector equals
/// </summary>
public static bool EqualsEpsilon(this Vector3 l, Vector3 r, float epsilon)
{
return
MathfEx.Approx(l.x, r.x, epsilon) &&
MathfEx.Approx(l.y, r.y, epsilon) &&
MathfEx.Approx(l.z, r.z, epsilon);
}
/// <summary>
/// Convert a vector to float array
/// </summary>
public static float[] ToFloatArray(this Vector3 v3)
{
return new float[3] { v3.x, v3.y, v3.z };
}
/// <summary>
/// Convert a float 3 array to vector
/// </summary>
public static Vector3 ToVector3(this float[] floatArray)
{
return new Vector3(floatArray[0], floatArray[1], floatArray[2]);
}
/// <summary>
/// Convert a vector array to float array
/// </summary>
public static float[] ToFloatArray(this Vector3[] v3Array)
{
float[] result = new float[v3Array.Length * 3];
for (int i = 0; i < v3Array.Length; i++)
{
result[i * 3] = v3Array[i].x;
result[i * 3 + 1] = v3Array[i].y;
result[i * 3 + 2] = v3Array[i].z;
}
return result;
}
/// <summary>
/// Convert a float array to vector 3 array
/// </summary>
public static Vector3[] ToVector3Array(this float[] floatArray)
{
var v3Array = new Vector3[floatArray.Length / 3];
for (int i = 0; i < v3Array.Length; i++)
{
v3Array[i] = new Vector3(floatArray[i * 3], floatArray[i * 3 + 1], floatArray[i * 3 + 2]);
}
return v3Array;
}
/// <summary>
///
/// </summary>
public static Color ToColor(this UInt32 _color)
{
Color c = new Color();
c.r = (_color >> 16) / 255.0f;
_color %= (256 * 256);
c.g = (_color >> 8) / 255.0f;
_color %= 256;
c.b = (_color >> 0) / 255.0f;
return c;
}
#endregion
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/XUnityExtensions.cs
|
C#
|
asf20
| 2,456
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GFramework
{
/// <summary>
/// Update scheduler to shedule a specific job
/// </summary>
public class JobScheduler
{
/// <summary>
/// A single job
/// </summary>
class Job
{
// Interval of update
public int intervalMs;
// Next update tick milestone
public int nextRunTime;
// The job itself
public Func<object, bool> callback;
// Parameters for the callback
public object @params;
}
// Time precision multiplier to compare
public float timePrecisionMultiplier { get; set; }
// Job list
private Dictionary<string, Job> jobList = new Dictionary<string, Job>();
/// <summary>
/// Get number of jobs
/// </summary>
public int Count { get { return jobList.Count; } }
/// <summary>
///
/// </summary>
public JobScheduler()
{
timePrecisionMultiplier = 1.0f;
}
/// <summary>
/// Add a single job
/// </summary>
public void AddJob(string jobName, Func<object, bool> callback, int firstInMs, int regularInMs, object @params)
{
Job job = new Job();
job.intervalMs = regularInMs;
job.nextRunTime = Environment.TickCount + firstInMs;
job.callback = callback;
job.@params = @params;
jobList.Add(jobName, job);
}
/// <summary>
/// Remove a job
/// </summary>
public void RemoveJob(string jobName)
{
if (jobList.ContainsKey(jobName))
jobList.Remove(jobName);
}
/// <summary>
///
/// </summary>
public bool HasJob(string jobName)
{
return jobList.ContainsKey(jobName);
}
/// <summary>
/// Update time to execute job
/// </summary>
/// <returns>Return next tick inverval to schedule next job</returns>
public int Update()
{
List<string> removeJobs = null;
int curTime = Environment.TickCount;
int nearestRunTime = int.MaxValue;
foreach (var pair in jobList)
{
Job job = pair.Value;
bool isPass = false;
if (timePrecisionMultiplier < 1)
{
if ((int)Math.Round(curTime * timePrecisionMultiplier) >= (int)Math.Round(job.nextRunTime * timePrecisionMultiplier))
isPass = true;
}
else if( curTime >= job.nextRunTime )
{
isPass = true;
}
if (isPass)
{
// Job call and remove if return false
if (!job.callback(job.@params))
{
if (removeJobs == null)
removeJobs = new List<string>();
removeJobs.Add(pair.Key);
}
else
{
// calculate nearest update time
job.nextRunTime = curTime + job.intervalMs;
if (job.nextRunTime < nearestRunTime)
nearestRunTime = job.nextRunTime;
}
}
else
{
// calculate nearest update time
if (job.nextRunTime < nearestRunTime)
nearestRunTime = job.nextRunTime;
}
}
// Remove the jobs in remove list
if (removeJobs != null && removeJobs.Count > 0)
{
foreach (var key in removeJobs)
jobList.Remove(key);
}
return nearestRunTime == int.MaxValue ? int.MaxValue : nearestRunTime - curTime;
}
/// <summary>
/// Force run all jobs
/// </summary>
public void RunAllJobsNow()
{
foreach (var pair in jobList)
{
pair.Value.callback(pair.Value.@params);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/JobScheduler.cs
|
C#
|
asf20
| 3,401
|
using UnityEngine;
using System.Collections;
public class EffectRepawner : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/EffectRepawner.cs
|
C#
|
asf20
| 210
|
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using GFramework;
[Serializable]
public class FastColliderNode
{
public Transform transform;
public string name;
public Vector3 firstPt;
public Vector3 lastPt;
public float radius;
public void Init(string name, Transform transform)
{
this.name = name;
this.firstPt = Vector3.right;
this.lastPt = -Vector3.right;
this.radius = 0.5f;
this.transform = transform;
}
public Vector3 MulVec3(Vector3 v1, Vector3 v2)
{
return new Vector3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z);
}
public Vector3 GetWorldFirstPt()
{
return (transform.rotation * MulVec3(firstPt, transform.lossyScale)) + transform.position;
}
public Vector3 GetWorldLastPt()
{
return (transform.rotation * MulVec3(lastPt, transform.lossyScale)) + transform.position;
}
public Vector3 GetWorldCenter()
{
Vector3 center = firstPt + (lastPt - firstPt) * 0.5f;
return (transform.rotation * MulVec3(center, transform.lossyScale)) + transform.position;
}
public float GetWorldRadius()
{
return radius * transform.lossyScale.x;
}
public bool IsLineSegmentIntersect(Vector3 lineStart, Vector3 lineEnd, out Vector3 intersectPt)
{
Vector3 wFirstPt = GetWorldFirstPt();
Vector3 wLastPt = GetWorldLastPt();
float wRadius = GetWorldRadius();
Vector3 ptCollider;
float sqrDistance = MathfEx.SqrDistanceSegmentToSegment(lineStart, lineEnd, wFirstPt, wLastPt, out intersectPt, out ptCollider);
return sqrDistance < (wRadius * wRadius);
}
public bool IsSphereOverlapped(Vector3 origin, float radius)
{
Vector3 wFirstPt = GetWorldFirstPt();
Vector3 wLastPt = GetWorldLastPt();
float wRadius = GetWorldRadius();
int closestPoint;
float sqrDistance = MathfEx.SqrDistancePointToSegment(origin, wFirstPt, wLastPt, out closestPoint);
return sqrDistance < ((wRadius + radius) * (wRadius + radius));
}
}
public class FastCollider : MonoBehaviour {
public List<FastColliderNode> colliderNodes;
private Transform _transform;
void Awake()
{
_transform = transform;
}
//void OnDrawGizmos()
//{
// return;
// foreach (var node in colliderNodes)
// {
// Matrix4x4 localMatrix = new Matrix4x4();
// Vector3 diff = node.lastPt - node.firstPt;
// float length = diff.magnitude;
// localMatrix.SetTRS(node.firstPt + (diff * 0.5f), diff.sqrMagnitude > 0 ? Quaternion.LookRotation(diff, Vector3.up) : Quaternion.identity, transform.lossyScale);
// Gizmos.matrix = transform.localToWorldMatrix * localMatrix;
// Gizmos.DrawWireCube(Vector3.zero, new Vector3(node.radius * 2, node.radius * 2, length));
// Gizmos.color = Color.red;
// Gizmos.DrawCube(Vector3.zero, new Vector3(0.01f, 0.01f, length));
// }
//}
public bool IsLineSegmentIntersect(Vector3 lineStart, Vector3 lineEnd, out Vector3 intersectPt)
{
foreach (var node in colliderNodes)
{
if (node.IsLineSegmentIntersect(lineStart, lineEnd, out intersectPt))
return true;
}
intersectPt = Vector3.zero;
return false;
}
public bool IsSphereOverlapped(Vector3 origin, float radius)
{
foreach (var node in colliderNodes)
{
if (node.IsSphereOverlapped(origin, radius))
return true;
}
return false;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/FastCollider.cs
|
C#
|
asf20
| 3,354
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace GFramework
{
/// <summary>
/// Event handler response value
/// </summary>
public enum EventResponse
{
Block,
PassThrough,
}
/// <summary>
/// Base class for event data
/// </summary>
public class EventBase
{
public UnityEngine.Object source;
public UnityEngine.Object target;
}
/// <summary>
/// Base class key event handler
/// </summary>
public class EventHandler<TEvent> where TEvent : EventBase
{
public delegate EventResponse EventDelegate();
public delegate EventResponse EventDelegateWithParam(TEvent e);
private EventDelegate _delegate;
private EventDelegateWithParam _delegateParam;
protected EventHandler(EventDelegate @delegate)
{
_delegate = @delegate;
_delegateParam = null;
}
public EventHandler(EventDelegateWithParam @delegate)
{
_delegate = null;
_delegateParam = @delegate;
}
public EventResponse Execute(TEvent e)
{
if (_delegateParam != null)
{
return _delegateParam(e);
}
if (_delegate != null)
return OnExecute(e, _delegate);
return EventResponse.PassThrough;
}
protected virtual EventResponse OnExecute(TEvent e, EventDelegate @delegate)
{
_delegate();
return EventResponse.PassThrough;
}
}
/// <summary>
/// Event dispatcher base class
/// </summary>
/// <typeparam name="TID"></typeparam>
/// <typeparam name="TEvent"></typeparam>
public class EventDispatcher<TID, TEvent> where TEvent : EventBase
{
private MultiPriorityMap<TID, EventHandler<TEvent>> eventsMap;
public EventDispatcher()
{
eventsMap = new MultiPriorityMap<TID, EventHandler<TEvent>>();
}
public EventDispatcher(IEqualityComparer<TID> comparer)
{
eventsMap = new MultiPriorityMap<TID, EventHandler<TEvent>>(comparer);
}
public void AddEventHandler(TID eventId, int priority, EventHandler<TEvent> handler)
{
eventsMap.Add(eventId, priority, handler);
}
public void AddEventHandler(TID eventId, EventHandler<TEvent> handler)
{
eventsMap.Add(eventId, 1, handler);
}
public EventResponse Dispatch(TID eventId, TEvent @event)
{
foreach (var @delegate in eventsMap.GetValueAsOrderedList(eventId))
{
if (@delegate.Execute(@event) == EventResponse.Block)
return EventResponse.Block;
}
return EventResponse.PassThrough;
}
public IEnumerable<TID> IDs
{
get
{
return this.eventsMap.Keys;
}
}
public bool Contains(TID eventId)
{
return this.eventsMap.ContainsKey(eventId);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/EventDispatcher.cs
|
C#
|
asf20
| 2,704
|
/// <summary>
/// iTweenHinting (iT) - An iTween(http://itween.pixelplacement.com) helper class that store all parameters of all tweening function to allow for code hinting/discovery.
/// Tested compatibility with iTween Version: 2.0.37
/// </summary>
//
// released under MIT License
// http://www.opensource.org/licenses/mit-license.php
//
//@author Devin Reimer
//@website http://blog.almostlogical.com
/*
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public static class iT
{
/// <summary>Instantly changes the amount(transparency) of a camera fade and then returns it back over time with FULL customization options.</summary>
public static class CameraFadeFrom
{
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for how transparent the Texture2D that the camera fade uses is.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Changes the amount(transparency) of a camera fade over time with FULL customization options.</summary>
public static class CameraFadeTo
{
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for how transparent the Texture2D that the camera fade uses is.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Returns a value to an 'oncallback' method interpolated between the supplied 'from' and 'to' values for application as desired. Requires an 'onupdate' callback that accepts the same type as the supplied 'from' and 'to' properties.</summary>
public static class ValueTo
{
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> or <see cref="Vector3"/> or <see cref="Vector2"/> or <see cref="Color"/> or <see cref="Rect"/> for the starting value.</summary>
public const string from = "from";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> or <see cref="Vector3"/> or <see cref="Vector2"/> or <see cref="Color"/> or <see cref="Rect"/> for the ending value.</summary>
public const string to = "to";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed (only works with Vector2, Vector3, and Floats)</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Changes a GameObject's alpha value instantly then returns it to the provided alpha over time with FULL customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation. Identical to using ColorFrom and using the "a" parameter.</summary>
public static class FadeFrom
{
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the initial alpha value of the animation.</summary>
public const string alpha = "alpha";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the initial alpha value of the animation.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.</summary>
public const string includechildren = "includechildren";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Changes a GameObject's alpha value over time with FULL customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation. Identical to using ColorTo and using the "a" parameter.</summary>
public static class FadeTo
{
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the final alpha value of the animation.</summary>
public const string alpha = "alpha";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the final alpha value of the animation.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.</summary>
public const string includechildren = "includechildren";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Changes a GameObject's color values instantly then returns them to the provided properties over time with FULL customization options. If a GUIText or GUITexture component is attached, it will become the target of the animation.</summary>
public static class ColorFrom
{
/// <summary>A <see cref="Color"/> to change the GameObject's color to.</summary>
public const string color = "color";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color red.</summary>
public const string r = "r";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.</summary>
public const string g = "g";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.</summary>
public const string b = "b";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the alpha.</summary>
public const string a = "a";
/// <summary>A <see cref="NamedColorValue"/> or <see cref="System.String"/> for the individual setting of the alpha.</summary>
public const string namedcolorvalue = "namedcolorvalue";
/// <summary>A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.</summary>
public const string includechildren = "includechildren";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Changes a GameObject's color values over time with FULL customization options. If a GUIText or GUITexture component is attached, they will become the target of the animation.</summary>
public static class ColorTo
{
/// <summary>A <see cref="Color"/> to change the GameObject's color to.</summary>
public const string color = "color";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color red.</summary>
public const string r = "r";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.</summary>
public const string g = "g";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.</summary>
public const string b = "b";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the alpha.</summary>
public const string a = "a";
/// <summary>A <see cref="NamedColorValue"/> or <see cref="System.String"/> for the individual setting of the alpha.</summary>
public const string namedcolorvalue = "namedcolorvalue";
/// <summary>A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.</summary>
public const string includechildren = "includechildren";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Instantly changes an AudioSource's volume and pitch then returns it to it's starting volume and pitch over time with FULL customization options. Default AudioSource attached to GameObject will be used (if one exists) if not supplied. </summary>
public static class AudioFrom
{
/// <summary>A <see cref="AudioSource"/> for which AudioSource to use.</summary>
public const string audiosource = "audiosource";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the target level of volume.</summary>
public const string volume = "volume";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the target pitch.</summary>
public const string pitch = "pitch";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Fades volume and pitch of an AudioSource with FULL customization options. Default AudioSource attached to GameObject will be used (if one exists) if not supplied. </summary>
public static class AudioTo
{
/// <summary>A <see cref="AudioSource"/> for which AudioSource to use.</summary>
public const string audiosource = "audiosource";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the target level of volume.</summary>
public const string volume = "volume";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the target pitch.</summary>
public const string pitch = "pitch";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Plays an AudioClip once based on supplied volume and pitch and following any delay with FULL customization options. AudioSource is optional as iTween will provide one.</summary>
public static class Stab
{
/// <summary>A <see cref="AudioClip"/> for a reference to the AudioClip to be played.</summary>
public const string audioclip = "audioclip";
/// <summary>A <see cref="AudioSource"/> for which AudioSource to use</summary>
public const string audiosource = "audiosource";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the target level of volume.</summary>
public const string volume = "volume";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the target pitch.</summary>
public const string pitch = "pitch";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the action will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Instantly rotates a GameObject to look at a supplied Transform or Vector3 then returns it to it's starting rotation over time with FULL customization options. </summary>
public static class LookFrom
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.String"/>. Restricts rotation to the supplied axis only.</summary>
public const string axis = "axis";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Rotates a GameObject to look at a supplied Transform or Vector3 over time with FULL customization options.</summary>
public static class LookTo
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.String"/>. Restricts rotation to the supplied axis only.</summary>
public const string axis = "axis";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Changes a GameObject's position over time to a supplied destination with FULL customization options.</summary>
public static class MoveTo
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for a point in space the GameObject will animate to.</summary>
public const string position = "position";
/// <summary>A <see cref="Transform[]"/> or <see cref="Vector3[]"/> for a list of points to draw a Catmull-Rom through for a curved animation path.</summary>
public const string path = "path";
/// <summary>A <see cref="System.Boolean"/> for whether to automatically generate a curve from the GameObject's current position to the beginning of the path. True by default.</summary>
public const string movetopath = "movetopath";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.</summary>
public const string orienttopath = "orienttopath";
/// <summary>A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".</summary>
public const string looktime = "looktime";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for how much of a percentage to look ahead on a path to influence how strict "orientopath" is.</summary>
public const string lookahead = "lookahead";
/// <summary>A <see cref="System.String"/>. Restricts rotation to the supplied axis only.</summary>
public const string axis = "axis";
/// <summary>A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.</summary>
public const string islocal = "islocal";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Instantly changes a GameObject's position to a supplied destination then returns it to it's starting position over time with FULL customization options.</summary>
public static class MoveFrom
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for a point in space the GameObject will animate to.</summary>
public const string position = "position";
/// <summary>A <see cref="Transform[]"/> or <see cref="Vector3[]"/> for a list of points to draw a Catmull-Rom through for a curved animation path.</summary>
public const string path = "path";
/// <summary>A <see cref="System.Boolean"/> for whether to automatically generate a curve from the GameObject's current position to the beginning of the path. True by default.</summary>
public const string movetopath = "movetopath";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.</summary>
public const string orienttopath = "orienttopath";
/// <summary>A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".</summary>
public const string looktime = "looktime";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for how much of a percentage to look ahead on a path to influence how strict "orientopath" is.</summary>
public const string lookahead = "lookahead";
/// <summary>A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.</summary>
public const string islocal = "islocal";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Translates a GameObject's position over time with FULL customization options.</summary>
public static class MoveAdd
{
/// <summary>A <see cref="Vector3"/> for the amount of change in position to move the GameObject.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.</summary>
public const string orienttopath = "orienttopath";
/// <summary>A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".</summary>
public const string looktime = "looktime";
/// <summary>A <see cref="System.String"/>. Restricts rotation to the supplied axis only.</summary>
public const string axis = "axis";
/// <summary>A <see cref="Space"/> or <see cref="System.String"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.</summary>
public const string space = "space";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Adds the supplied coordinates to a GameObject's position with FULL customization options.</summary>
public static class MoveBy
{
/// <summary>A <see cref="Vector3"/> for the amount of change in position to move the GameObject.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.</summary>
public const string orienttopath = "orienttopath";
/// <summary>A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".</summary>
public const string looktime = "looktime";
/// <summary>A <see cref="System.String"/>. Restricts rotation to the supplied axis only.</summary>
public const string axis = "axis";
/// <summary>A <see cref="Space"/> or <see cref="System.String"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.</summary>
public const string space = "space";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Changes a GameObject's scale over time with FULL customization options.</summary>
public static class ScaleTo
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for the final scale.</summary>
public const string scale = "scale";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Instantly changes a GameObject's scale then returns it to it's starting scale over time with FULL customization options.</summary>
public static class ScaleFrom
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for the final scale.</summary>
public const string scale = "scale";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Adds to a GameObject's scale over time with FULL customization options.</summary>
public static class ScaleAdd
{
/// <summary>A <see cref="Vector3"/> for the amount to be added to the GameObject's current scale.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Multiplies a GameObject's scale over time with FULL customization options.</summary>
public static class ScaleBy
{
/// <summary>A <see cref="Vector3"/> for the amount to be multiplied to the GameObject's current scale.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Rotates a GameObject to the supplied Euler angles in degrees over time with FULL customization options.</summary>
public static class RotateTo
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for the target Euler angles in degrees to rotate to.</summary>
public const string rotation = "rotation";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.</summary>
public const string islocal = "islocal";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Instantly changes a GameObject's Euler angles in degrees then returns it to it's starting rotation over time (if allowed) with FULL customization options.</summary>
public static class RotateFrom
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for the target Euler angles in degrees to rotate to.</summary>
public const string rotation = "rotation";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.</summary>
public const string islocal = "islocal";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Adds supplied Euler angles in degrees to a GameObject's rotation over time with FULL customization options.</summary>
public static class RotateAdd
{
/// <summary>A <see cref="Vector3"/> for the amount of Euler angles in degrees to add to the current rotation of the GameObject.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="Space"/> or <see cref="System.String"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.</summary>
public const string space = "space";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Multiplies supplied values by 360 and rotates a GameObject by calculated amount over time with FULL customization options.</summary>
public static class RotateBy
{
/// <summary>A <see cref="Vector3"/> for the amount to be multiplied by 360 to rotate the GameObject.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="Space"/> or <see cref="System.String"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.</summary>
public const string space = "space";
/// <summary>A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.</summary>
public const string islocal = "islocal";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed</summary>
public const string speed = "speed";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.</summary>
public const string easetype = "easetype";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Randomly shakes a GameObject's position by a diminishing amount over time with FULL customization options.</summary>
public static class ShakePosition
{
/// <summary>A <see cref="Vector3"/> for the magnitude of shake.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.</summary>
public const string islocal = "islocal";
/// <summary>A <see cref="Space"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.</summary>
public const string space = "space";
/// <summary>A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.</summary>
public const string orienttopath = "orienttopath";
/// <summary>A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".</summary>
public const string looktime = "looktime";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with shakes)</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Randomly shakes a GameObject's scale by a diminishing amount over time with FULL customization options.</summary>
public static class ShakeScale
{
/// <summary>A <see cref="Vector3"/> for the magnitude of shake.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with shakes)</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Randomly shakes a GameObject's rotation by a diminishing amount over time with FULL customization options.</summary>
public static class ShakeRotation
{
/// <summary>A <see cref="Vector3"/> for the magnitude of shake.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.</summary>
public const string z = "z";
/// <summary>A <see cref="Space"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.</summary>
public const string space = "space";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with shakes)</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Applies a jolt of force to a GameObject's position and wobbles it back to its initial position with FULL customization options.</summary>
public static class PunchPosition
{
/// <summary>A <see cref="Vector3"/> for the magnitude of shake.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.</summary>
public const string z = "z";
/// <summary>A <see cref="Space"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.</summary>
public const string space = "space";
/// <summary>A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget".</summary>
public const string looktime = "looktime";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with punches)</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Applies a jolt of force to a GameObject's rotation and wobbles it back to its initial rotation with FULL customization options.</summary>
public static class PunchRotation
{
/// <summary>A <see cref="Vector3"/> for the magnitude of shake.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.</summary>
public const string z = "z";
/// <summary>A <see cref="Space"/> for applying the transformation in either the world coordinate or local cordinate system. Defaults to local space.</summary>
public const string space = "space";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with punches)</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Applies a jolt of force to a GameObject's scale and wobbles it back to its initial scale with FULL customization options.</summary>
public static class PunchScale
{
/// <summary>A <see cref="Vector3"/> for the magnitude of shake.</summary>
public const string amount = "amount";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x magnitude.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y magnitude.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z magnitude.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.</summary>
public const string delay = "delay";
/// <summary>A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed. (only "loop" is allowed with punches)</summary>
public const string looptype = "looptype";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.</summary>
public const string onstart = "onstart";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.</summary>
public const string onstarttarget = "onstarttarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.</summary>
public const string onstartparams = "onstartparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch on every step of the animation.</summary>
public const string onupdate = "onupdate";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.</summary>
public const string onupdatetarget = "onupdatetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.</summary>
public const string onupdateparams = "onupdateparams";
/// <summary>A <see cref="System.String"/> for the name of a function to launch at the end of the animation.</summary>
public const string oncomplete = "oncomplete";
/// <summary>A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.</summary>
public const string oncompletetarget = "oncompletetarget";
/// <summary>A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.</summary>
public const string oncompleteparams = "oncompleteparams";
}
/// <summary>Similar to FadeTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType. </summary>
public static class FadeUpdate
{
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the final alpha value of the animation.</summary>
public const string alpha = "alpha";
/// <summary>A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.</summary>
public const string includechildren = "includechildren";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
}
/// <summary>Similar to ColorTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType. </summary>
public static class ColorUpdate
{
/// <summary>A <see cref="Color"/> to change the GameObject's color to.</summary>
public const string color = "color";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color red.</summary>
public const string r = "r";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.</summary>
public const string g = "g";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.</summary>
public const string b = "b";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the alpha.</summary>
public const string a = "a";
/// <summary>A <see cref="NamedColorValue"/> or <see cref="System.String"/> for the individual setting of the alpha.</summary>
public const string namedcolorvalue = "namedcolorvalue";
/// <summary>A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.</summary>
public const string includechildren = "includechildren";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
}
/// <summary>Similar to AudioTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType. </summary>
public static class AudioUpdate
{
/// <summary>A <see cref="AudioSource"/> for which AudioSource to use.</summary>
public const string audiosource = "audiosource";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the target level of volume.</summary>
public const string volume = "volume";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the target pitch.</summary>
public const string pitch = "pitch";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
}
/// <summary>Similar to RotateTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType. </summary>
public static class RotateUpdate
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for the target Euler angles in degrees to rotate to.</summary>
public const string rotation = "rotation";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False by default.</summary>
public const string islocal = "islocal";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
}
/// <summary>Similar to ScaleTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType. </summary>
public static class ScaleUpdate
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for the final scale.</summary>
public const string scale = "scale";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
}
/// <summary>Similar to MoveTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType. </summary>
public static class MoveUpdate
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for a point in space the GameObject will animate to.</summary>
public const string position = "position";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis.</summary>
public const string x = "x";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis.</summary>
public const string y = "y";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis.</summary>
public const string z = "z";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
/// <summary>A <see cref="System.Boolean"/> for whether to animate in world space or relative to the parent. False be default.</summary>
public const string islocal = "islocal";
/// <summary>A <see cref="System.Boolean"/> for whether or not the GameObject will orient to its direction of travel. False by default.</summary>
public const string orienttopath = "orienttopath";
/// <summary>A <see cref="Vector3"/> or A <see cref="Transform"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the object will take to look at either the "looktarget" or "orienttopath".</summary>
public const string looktime = "looktime";
/// <summary>A <see cref="System.String"/>. Restricts rotation to the supplied axis only.</summary>
public const string axis = "axis";
}
/// <summary>Similar to LookTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType. </summary>
public static class LookUpdate
{
/// <summary>A <see cref="Transform"/> or <see cref="Vector3"/> for a target the GameObject will look at.</summary>
public const string looktarget = "looktarget";
/// <summary>A <see cref="System.String"/>. Restricts rotation to the supplied axis only.</summary>
public const string axis = "axis";
/// <summary>A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.</summary>
public const string time = "time";
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/iTweenHinting.cs
|
C#
|
asf20
| 111,532
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
public class Encryption
{
public static System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
public static RijndaelManaged GetRijndaelManaged(String secretKey)
{
var keyBytes = new byte[16];
var secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
Array.Copy(secretKeyBytes, keyBytes, Math.Min(keyBytes.Length, secretKeyBytes.Length));
return new RijndaelManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
KeySize = 128,
BlockSize = 128,
Key = keyBytes,
IV = keyBytes
};
}
public static byte[] Encrypt(byte[] plainBytes, RijndaelManaged rijndaelManaged)
{
return rijndaelManaged.CreateEncryptor()
.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
}
public static byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
{
return rijndaelManaged.CreateDecryptor()
.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
}
/// <summary>
/// Encrypts plaintext using AES 128bit key and a Chain Block Cipher and returns a base64 encoded string
/// </summary>
/// <param name="plainText">Plain text to encrypt</param>
/// <param name="key">Secret key</param>
/// <returns>Base64 encoded string</returns>
public static String Encrypt(String plainText, String key)
{
var plainBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(Encrypt(plainBytes, GetRijndaelManaged(key)));
}
/// <summary>
/// Decrypts a base64 encoded string using the given key (AES 128bit key and a Chain Block Cipher)
/// </summary>
/// <param name="encryptedText">Base64 Encoded String</param>
/// <param name="key">Secret Key</param>
/// <returns>Decrypted String</returns>
public static String Decrypt(String encryptedText, String key)
{
var encryptedBytes = Convert.FromBase64String(encryptedText);
return Encoding.UTF8.GetString(Decrypt(encryptedBytes, GetRijndaelManaged(key)));
}
public static string GetMD5Hash(string plainText)
{
return BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(plainText))).Replace("-", String.Empty);
}
public static string GetMD5Hash(byte[] plainBytes)
{
return BitConverter.ToString(md5.ComputeHash(plainBytes)).Replace("-", String.Empty);
}
/// <summary>
/// Encrypts plaintext using AES 128bit key and a Chain Block Cipher and returns a base64 encoded string
/// Include checksum in the encryption data to prevent data modification
/// </summary>
/// <param name="plainText">Plain text to encrypt</param>
/// <param name="key">Secret key</param>
/// <returns>Base64 encoded string</returns>
public static String EncryptWithChecksum(String plainText, String key)
{
string hash = GetMD5Hash(plainText);
string plainTextWithHash = hash + "," + plainText;
return Encrypt(plainTextWithHash, key);
}
/// <summary>
/// Decrypts a base64 encoded string using the given key (AES 128bit key and a Chain Block Cipher)
/// Extract hash value from the data, if hash value does not match with the hash calculation from the string the value is rejected
/// </summary>
/// <param name="encryptedText">Base64 Encoded String</param>
/// <param name="key">Secret Key</param>
/// <returns>Decrypted String</returns>
public static bool DecryptWithChecksum(String encryptedText, String key, out String result)
{
result = null;
// Decrypt plain text with include hash
String plainTextWithHash = Decrypt(encryptedText, key);
int pos = plainTextWithHash.IndexOf(',');
if (pos <= 0)
return false;
// extract the hash and plain text
string hash = plainTextWithHash.Substring(0, pos);
string plainText = plainTextWithHash.Substring(pos + 1);
// Compare the hash
if (!hash.Equals(GetMD5Hash(plainText)))
return false;
// return result
result = plainText;
return true;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/Encryption.cs
|
C#
|
asf20
| 4,038
|
//#define USE_SharpZipLib
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SimpleJSON
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem) { }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break; } }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value, out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value, out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value, out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value, out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value) ? "true" : "false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null) ? null : d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a, b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach (char c in aText)
{
switch (c)
{
case '\\': result += "\\\\"; break;
case '\"': result += "\\\""; break;
case '\n': result += "\\n"; break;
case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break;
case '\b': result += "\\b"; break;
case '\f': result += "\\f"; break;
default: result += c; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
if (stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't': Token += '\t'; break;
case 'r': Token += '\r'; break;
case 'n': Token += '\n'; break;
case 'b': Token += '\b'; break;
case 'f': Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default: Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) { }
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToFile(string aFileName)
{
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using (var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch (type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for (int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for (int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using (var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromFile(string aFileName)
{
using (var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex < 0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get { return new JSONLazyCreator(this); }
set { m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach (JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach (JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix + " ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for (int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey, value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix + " ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach (string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize(System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add(JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add(string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a, b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/SimpleJSON.cs
|
C#
|
asf20
| 24,690
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace GFramework
{
/// <summary>
///
/// </summary>
public static class IDictionaryExtensions
{
/// <summary>
/// Get all relate keys by value
/// </summary>
public static bool TryGetKeysByValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TValue value, out TKey[] keys)
{
if (dictionary == null)
throw new ArgumentNullException("Dictionary is null");
keys = dictionary.Where(p => p.Value.Equals(value)).Select(p => p.Key).ToArray();
if (keys.Length == 0)
return false;
return true;
}
/// <summary>
/// Get single key by value
/// </summary>
public static bool TryGetKeyByValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TValue value, out TKey key)
{
if (dictionary == null)
throw new ArgumentNullException("Dictionary is null");
IEnumerable<TKey> find = dictionary.Where(p => p.Value.Equals(value)).Select(p => p.Key);
if (find.Any() == false)
{
key = default(TKey);
return false;
}
key = find.First();
return true;
}
}
public class ReadOnlyDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
private bool _locked = false;
public ReadOnlyDictionary()
{
}
public ReadOnlyDictionary(Dictionary<TKey, TValue> dictionary) : base (dictionary)
{
}
public new void Add(TKey key, TValue value)
{
if (!_locked)
{
base.Add(key, value);
}
else
{
throw new AccessViolationException();
}
}
public new TValue this[TKey key]
{
get
{
return base[key];
}
set
{
if (!_locked)
{
base[key] = value;
}
else
{
throw new AccessViolationException();
}
}
}
public void Lock()
{
_locked = true;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/ReadOnlyDictionary.cs
|
C#
|
asf20
| 1,891
|
#region Copyright
// ----------------------------------------------------------------------------
//
// Modifications made by: Alex Kring (c) 2011, for SimplePath
//
// OpenSteerDotNet - pure .net port
// Port by Simon Oliver - http://www.handcircus.com
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2003, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
#endregion
using UnityEngine;
using System.Collections;
using System;
using System.Text;
namespace GFramework
{
public class Pathway
{
// given a distance along the path, convert it to a point on the path
public virtual Vector3 MapPathDistanceToPoint(float pathDistance) { return Vector3.zero; }
// Given an arbitrary point, convert it to a distance along the path.
public virtual float MapPointToPathDistance(Vector3 point) { return 0; }
}
public class PolylinePathway : Pathway
{
#region Fields
int pointCount;
Vector3[] points;
float segmentLength;
float segmentProjection;
Vector3 local;
Vector3 chosen;
Vector3 segmentNormal;
float[] lengths;
Vector3[] normals;
float totalPathLength;
#endregion
#region Properties
public Vector3[] Points
{
get { return points; }
}
public int PointCount
{
get { return pointCount; }
}
#endregion
public PolylinePathway()
{
}
public PolylinePathway(int _pointCount)
{
Initialize(_pointCount, null);
}
// construct a PolylinePathway given the number of points (vertices),
// an array of points
public PolylinePathway(int _pointCount, Vector3[] _points)
{
Initialize(_pointCount, _points);
}
public void ReInitialize(int _pointCount, Vector3[] _points)
{
Initialize(_pointCount, _points);
}
// utility for constructors in derived classes
void Initialize(int _pointCount, Vector3[] _points)
{
// set data members, allocate arrays
pointCount = _pointCount;
totalPathLength = 0;
lengths = new float[pointCount];
points = new Vector3[pointCount];
normals = new Vector3[pointCount];
if (_points == null)
{
return;
}
// loop over all points
for (int i = 0; i < pointCount; i++)
{
// copy in point locations, closing cycle when appropriate
bool closeCycle = false;
int j = closeCycle ? 0 : i;
points[i] = _points[j];
// for the end of each segment
if (i > 0)
{
// compute the segment length
normals[i] = points[i] - points[i - 1];
lengths[i] = normals[i].magnitude;
// find the normalized vector parallel to the segment
normals[i] *= 1 / lengths[i];
// keep running total of segment lengths
totalPathLength += lengths[i];
}
}
}
// utility methods
// assessor for total path length;
public float GetTotalPathLength() { return totalPathLength; }
public override float MapPointToPathDistance(Vector3 point)
{
float d;
float minDistance = float.MaxValue;
float segmentLengthTotal = 0;
float pathDistance = 0;
for (int i = 1; i < pointCount; i++)
{
segmentLength = lengths[i];
segmentNormal = normals[i];
d = PointToSegmentDistance(point, points[i - 1], points[i]);
if (d < minDistance)
{
minDistance = d;
pathDistance = segmentLengthTotal + segmentProjection;
}
segmentLengthTotal += segmentLength;
}
// return distance along path of onPath point
return pathDistance;
}
public override Vector3 MapPathDistanceToPoint(float pathDistance)
{
// clip or wrap given path distance
float remaining = pathDistance;
if (pathDistance < 0) return points[0];
if (pathDistance >= totalPathLength) return points[pointCount - 1];
// step through segments, subtracting off segment lengths until
// locating the segment that contains the original pathDistance.
// Interpolate along that segment to find 3d point value to return.
Vector3 result = Vector3.zero;
for (int i = 1; i < pointCount; i++)
{
segmentLength = lengths[i];
if (segmentLength < remaining)
{
remaining -= segmentLength;
}
else
{
float ratio = remaining / segmentLength;
result = interpolate(ratio, points[i - 1], points[i]);
break;
}
}
return result;
}
// ----------------------------------------------------------------------------
// computes distance from a point to a line segment
//
// (I considered moving this to the vector library, but its too
// tangled up with the internal state of the PolylinePathway instance)
public float PointToSegmentDistance(Vector3 point, Vector3 ep0, Vector3 ep1)
{
// convert the test point to be "local" to ep0
local = point - ep0;
// find the projection of "local" onto "segmentNormal"
segmentProjection = Vector3.Dot(segmentNormal, local);
// handle boundary cases: when projection is not on segment, the
// nearest point is one of the endpoints of the segment
if (segmentProjection < 0)
{
chosen = ep0;
segmentProjection = 0;
return (point - ep0).magnitude;
}
if (segmentProjection > segmentLength)
{
chosen = ep1;
segmentProjection = segmentLength;
return (point - ep1).magnitude;
}
// otherwise nearest point is projection point on segment
chosen = segmentNormal * segmentProjection;
chosen += ep0;
return (point - chosen).magnitude;
}
public static float interpolate(float alpha, float x0, float x1)
{
return x0 + ((x1 - x0) * alpha);
}
public static Vector3 interpolate(float alpha, Vector3 x0, Vector3 x1)
{
return x0 + ((x1 - x0) * alpha);
}
public static Vector3 TruncateLength(Vector3 vec, float maxLength)
{
float length = vec.magnitude;
Vector3 returnVector = vec;
if (length > maxLength)
{
returnVector.Normalize();
returnVector *= maxLength;
}
return returnVector;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/PolylinePathway.cs
|
C#
|
asf20
| 7,331
|
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
public class SkinnedMeshCombinerUtility
{
/// <summary>
///
/// </summary>
public enum CombineMode
{
// Medium speed, largest number of bones, accurate for all type of skinned mesh
// Duplicate bone/bindpose for every mesh instances processing, so each instance has
// separate range of bone/bindpose
DuplicateBoneBindpose,
// Fastest speed, smallest number of bones, need standard bindpose in 3D editor tool
// All instances share the same bone/bindpose hierachy structure, so the bindpose must *BE*
// freezed to identity in 3D modeling tool for this option to work
SharedBoneBindpose,
// Slowest speed, medium number of bones, accurate for all type of skinned mesh
// Auto calculate overlapped bone/bindpose to share and prevent create new as much as possible,
// this calculation comsumes time for searching and matrix-comparation
CalculateOverlappedBoneBindpose,
}
/// <summary>
/// What to do when end combine
/// </summary>
public enum EndCombine
{
DestroyChild,
DeactiveChild,
DisableRenderer,
Nothing,
}
// Optimize type
public CombineMode optimizeType { get; private set; }
// End combine behaviour
public EndCombine endCombine { get; private set; }
// Hint for alloc optimize: maximum number of vertex per model
public int maxVertexHint { get; private set; }
// Hint for alloc optimize: maximum number of bones per model
public int maxBoneHint { get; private set; }
// Shared bone/bindpose (for OptimizeType.CalculateOverlappedBoneBindpose)
public SharedBoneBindposeGroups sharedGroups;
// Shared bone/bindpose (for OptimizeType.SharedBoneBindpose)
public Dictionary<Transform, int> boneIndexLookup;
// Combined bones list
public List<Transform> bones;
// Combined bonepose list, the same size with bones list
public List<Matrix4x4> bindposes;
// Combined boneweights, the same size with number of vertices
public List<BoneWeight> boneWeights;
// List mesh instance
public List<MeshInstance> meshInstances;
//Setting my Arrays for copies
public List<Material> materials;
/// <summary>
/// Mesh instance
/// </summary>
public struct MeshInstance
{
public Mesh mesh;
public int subMeshIndex;
}
/// <summary>
/// Bone/bindpose combination to share
/// </summary>
public class SharedBoneBindpose
{
public int index;
public Transform bone;
public Matrix4x4 bindpose;
}
/// <summary>
/// Manage to find item
/// </summary>
public class SharedBoneBindposeGroups
{
private Dictionary<Transform, List<SharedBoneBindpose>> lookup = new Dictionary<Transform, List<SharedBoneBindpose>>();
/// <summary>
/// Finds the specified bone/bindpose.
/// </summary>
public SharedBoneBindpose Find(Transform bone, Matrix4x4 bindpose)
{
// New bone/bindpose combination
SharedBoneBindpose boneBindpose = null;
List<SharedBoneBindpose> sharedGroups;
// Find
if (lookup.TryGetValue(bone, out sharedGroups))
{
boneBindpose = sharedGroups.Find(b => b.bindpose == bindpose);
}
return boneBindpose;
}
/// <summary>
/// Creates the specified bone.
/// </summary>
public SharedBoneBindpose Create(Transform bone, Matrix4x4 bindpose, int index)
{
SharedBoneBindpose boneBindpose = null;
List<SharedBoneBindpose> sharedGroups;
// Find
if (lookup.TryGetValue(bone, out sharedGroups))
{
boneBindpose = sharedGroups.Find(b => b.bindpose == bindpose);
}
else // Create groups
{
sharedGroups = new List<SharedBoneBindpose>();
lookup.Add(bone, sharedGroups);
}
// Create bone/bindpose
if (boneBindpose == null)
{
boneBindpose = new SharedBoneBindpose();
sharedGroups.Add(boneBindpose);
}
boneBindpose.bone = bone;
boneBindpose.bindpose = bindpose;
boneBindpose.index = index;
return boneBindpose;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SkinnedMeshCombineUtility"/> class.
/// </summary>
public SkinnedMeshCombinerUtility(CombineMode optimizeType, EndCombine endCombine, int maxVertexHint, int maxBoneHint)
{
this.optimizeType = optimizeType;
this.endCombine = endCombine;
if (this.optimizeType == CombineMode.CalculateOverlappedBoneBindpose)
sharedGroups = new SharedBoneBindposeGroups();
else if (this.optimizeType == CombineMode.SharedBoneBindpose)
boneIndexLookup = new Dictionary<Transform, int>();
this.bones = new List<Transform>(maxBoneHint);
this.bindposes = new List<Matrix4x4>(maxBoneHint);
this.boneWeights = new List<BoneWeight>(maxVertexHint);
this.meshInstances = new List<MeshInstance>();
this.materials = new List<Material>();
}
/// <summary>
/// Applies the specified sm renderer.
/// </summary>
private void Build(SkinnedMeshRenderer smRenderer)
{
//Setting Mesh
smRenderer.sharedMesh = CombineMeshInstance(meshInstances);
//Setting Bindposes
smRenderer.sharedMesh.bindposes = bindposes.ToArray();
//Setting BoneWeights
smRenderer.sharedMesh.boneWeights = boneWeights.ToArray();
//Setting bones
smRenderer.bones = bones.ToArray();
//Setting Materials
smRenderer.sharedMaterials = materials.ToArray();
//objRenderer.sharedMesh.RecalculateNormals();
//objRenderer.sharedMesh.RecalculateBounds();
// Log
//Debug.Log("Combine skinned mesh: type: " + optimizeType + "\nBones: " + bones.Count + ", bindpose: " + bindposes.Count);
}
/// <summary>
/// Combines the mesh instance.
/// </summary>
private Mesh CombineMeshInstance(List<MeshInstance> instances)
{
// Get total vertex count
int totalVertexCount = 0;
foreach (MeshInstance ins in instances)
totalVertexCount += ins.mesh.vertexCount;
// Extract resource
Vector3[] vertices = new Vector3[totalVertexCount];
Vector3[] normals = new Vector3[totalVertexCount];
Vector4[] tangents = new Vector4[totalVertexCount];
Vector2[] uv = new Vector2[totalVertexCount];
Vector2[] uv1 = new Vector2[totalVertexCount];
// Copy in to result
int vertexOffset = 0;
foreach (MeshInstance ins in instances)
{
int count = ins.mesh.vertexCount;
Array.Copy(ins.mesh.vertices, 0, vertices, vertexOffset, count);
Array.Copy(ins.mesh.normals, 0, normals, vertexOffset, count);
Array.Copy(ins.mesh.tangents, 0, tangents, vertexOffset, count);
Array.Copy(ins.mesh.uv, 0, uv, vertexOffset, count);
Array.Copy(ins.mesh.uv1, 0, uv1, vertexOffset, count);
vertexOffset += count;
}
// New mesh
Mesh mesh = new Mesh();
mesh.name = "SkinnedMeshCombiner";
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uv;
mesh.uv1 = uv1;
mesh.tangents = tangents;
// Setting sub-meshes base on number of instances
mesh.subMeshCount = instances.Count;
// Set triangle index
vertexOffset = 0;
for (int subMesh = 0; subMesh < instances.Count; subMesh++)
{
MeshInstance ins = instances[subMesh];
// Get source triangle index
int[] srcTriangles = ins.mesh.GetTriangles(ins.subMeshIndex);
int[] dstTriangles = new int[srcTriangles.Length];
// Increase index by vertex offset
for (int i = 0; i < srcTriangles.Length; i++)
dstTriangles[i] = srcTriangles[i] + vertexOffset;
// Set submesh triangles
mesh.SetTriangles(dstTriangles, subMesh);
// Increase offset
vertexOffset += ins.mesh.vertexCount;
}
// Mesh name
mesh.name = "Combined Mesh";
return mesh;
}
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear(SkinnedMeshRenderer smRenderer)
{
smRenderer.sharedMesh = null;
smRenderer.bones = null;
smRenderer.sharedMaterials = null;
}
/// <summary>
/// Combines the specified sm renderers.
/// </summary>
public void Combine(SkinnedMeshRenderer resultTarget, SkinnedMeshRenderer[] smRenderers)
{
if (smRenderers == null || smRenderers.Length == 0)
{
Debug.LogWarning("Combine skinned mesh: child renderers are null or empty");
return;
}
//Debug.Log("Combine skinned mesh: child " + smRenderers.Length );
// Temp values
int modeDuplicate_boneOffset = 0; // for CombineMode.SharedBoneBindpose
// Iterate all sub renderers
for (int i = 0; i < smRenderers.Length; i++)
{
//Getting one by one
SkinnedMeshRenderer smRenderer = smRenderers[i];
// Making changes to the Skinned Renderer
MeshInstance instance = new MeshInstance();
// Setting the Mesh for the instance
instance.mesh = smRenderer.sharedMesh;
// Getting all materials
Material[] sharedMaterials = smRenderer.sharedMaterials;
for (int t = 0; t < sharedMaterials.Length; t++)
materials.Add(sharedMaterials[t]);
//
if (smRenderer != null && smRenderer.sharedMesh != null)
{
//instance.transform = Matrix4x4.identity; // myTransform /*transform.worldToLocalMatrix */ * smRenderer.transform.localToWorldMatrix;
//Getting subMesh
for (int t = 0; t < smRenderer.sharedMesh.subMeshCount; t++)
{
instance.subMeshIndex = t;
meshInstances.Add(instance);
}
//Copying Bones
Transform[] smBones = smRenderer.bones;
Matrix4x4[] smBindposes = smRenderer.sharedMesh.bindposes;
BoneWeight[] smBoneweights = smRenderer.sharedMesh.boneWeights;
switch (optimizeType)
{
case CombineMode.CalculateOverlappedBoneBindpose:
{
//Copying Bones
for (int b = 0; b < smBones.Length; b++)
{
// New bone/bindpose combination
SharedBoneBindpose sharedBoneBindpose = sharedGroups.Find(smBones[b], smBindposes[b]);
if (sharedBoneBindpose != null)
continue;
// Create new bone/bindpose
sharedBoneBindpose = sharedGroups.Create(smBones[b], smBindposes[b], bones.Count);
//inserting bones in totalBones
bones.Add(smBones[b]);
//Recalculating BindPoses
bindposes.Add(smBindposes[b]);
//totalBindPoses[offset] = smRenderer.bones[x].worldToLocalMatrix * transform.localToWorldMatrix;
}
//RecalculateBoneWeights
for (int bw = 0; bw < smBoneweights.Length; bw++)
{
//Just Copying and changing the Bones Indexes !!
boneWeights.Add(RecalculateBoneIndexes(smBoneweights[bw], sharedGroups, smBones, smBindposes));
}
}
break;
case CombineMode.SharedBoneBindpose:
{
//Copying Bones
for (int b = 0; b < smBones.Length; b++)
{
// New bone/bindpose combination
if (boneIndexLookup.ContainsKey(smBones[b]))
continue;
// Add to lookup
boneIndexLookup.Add(smBones[b], bones.Count);
//inserting bones in totalBones
bones.Add(smBones[b]);
//Recalculating BindPoses
bindposes.Add(smBindposes[b]);
}
//RecalculateBoneWeights
for (int bw = 0; bw < smBoneweights.Length; bw++)
{
//Just Copying and changing the Bones Indexes !!
boneWeights.Add(RecalculateBoneIndexes(smBoneweights[bw], boneIndexLookup, smBones, smBindposes));
}
}
break;
case CombineMode.DuplicateBoneBindpose:
{
// May want to modify this if the renderer shares bones as unnecessary bones will get added.
foreach (BoneWeight bw in smBoneweights)
{
BoneWeight _bw = bw;
_bw.boneIndex0 += modeDuplicate_boneOffset;
_bw.boneIndex1 += modeDuplicate_boneOffset;
_bw.boneIndex2 += modeDuplicate_boneOffset;
_bw.boneIndex3 += modeDuplicate_boneOffset;
boneWeights.Add(_bw);
}
modeDuplicate_boneOffset += smBones.Length;
foreach (Transform bone in smBones)
bones.Add(bone);
for (int b = 0; b < smBones.Length; b++)
{
bindposes.Add(smBindposes[b]); // bones[b].worldToLocalMatrix * transform.localToWorldMatrix);
}
}
break;
}
// Disabling current SkinnedMeshRenderer
EndCombineChildRenderer(smRenderer);
}
}
// Build final mesh
Build(resultTarget);
}
/// <summary>
/// Called when [end combine].
/// </summary>
private void EndCombineChildRenderer(SkinnedMeshRenderer smRenderer)
{
switch (endCombine)
{
case EndCombine.DestroyChild:
UnityEngine.Object.Destroy(smRenderer.gameObject);
break;
case EndCombine.DeactiveChild:
smRenderer.gameObject.active = false;
break;
case EndCombine.DisableRenderer:
smRenderer.enabled = false;
break;
}
}
/// <summary>
/// Recalculates the bone indexes.
/// </summary>
private BoneWeight RecalculateBoneIndexes(BoneWeight bw, SharedBoneBindposeGroups sharedGroups, Transform[] smBones, Matrix4x4[] smBindposes)
{
Func<Transform, Matrix4x4, int> GetBoneIdx = (bone, bindpose) =>
{
SharedBoneBindpose shareBoneBindpose = sharedGroups.Find(bone, bindpose);
if (shareBoneBindpose != null)
return shareBoneBindpose.index;
return 0;
};
BoneWeight retBw = bw;
retBw.boneIndex0 = GetBoneIdx(smBones[bw.boneIndex0], smBindposes[bw.boneIndex0]);
retBw.boneIndex1 = GetBoneIdx(smBones[bw.boneIndex1], smBindposes[bw.boneIndex1]);
retBw.boneIndex2 = GetBoneIdx(smBones[bw.boneIndex2], smBindposes[bw.boneIndex2]);
retBw.boneIndex3 = GetBoneIdx(smBones[bw.boneIndex3], smBindposes[bw.boneIndex3]);
//retBw.boneIndex0 = 0;
//retBw.weight0 = 1;
//retBw.weight1 = retBw.weight2 = retBw.weight3 = 0;
//Debug.Log(bw.boneIndex0+ " " + bw.boneIndex1+ " " + bw.boneIndex2+ " " + bw.boneIndex3+ " " + ">" +
// retBw.boneIndex0 + " " + retBw.boneIndex1 + " " + retBw.boneIndex2 + " " + retBw.boneIndex3 + " " + ">" +
// retBw.weight0 + " " + retBw.weight1 + " " + retBw.weight2 + " " + retBw.weight3);
return retBw;
}
/// <summary>
/// Recalculates the bone indexes.
/// </summary>
private BoneWeight RecalculateBoneIndexes(BoneWeight bw, Dictionary<Transform, int> boneIndexLookup, Transform[] smBones, Matrix4x4[] smBindposes)
{
BoneWeight retBw = bw;
retBw.boneIndex0 = boneIndexLookup[smBones[bw.boneIndex0]];
retBw.boneIndex1 = boneIndexLookup[smBones[bw.boneIndex1]];
retBw.boneIndex2 = boneIndexLookup[smBones[bw.boneIndex2]];
retBw.boneIndex3 = boneIndexLookup[smBones[bw.boneIndex3]];
return retBw;
}
// public bool Approx(Vector3 val, Vector3 about)
// {
// return Mathf.Approximately(val.x, about.x) &&
// Mathf.Approximately(val.y, about.y) &&
// Mathf.Approximately(val.z, about.z);
// }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/SkinnedMeshCombinerUtility.cs
|
C#
|
asf20
| 14,905
|
/// <summary>
/// Object layer definations
/// </summary>
public class GlobalLayers
{
/// <summary>UI layer</summary>
public const int UI = 8;
public const int UIMask = 1 << UI;
/// <summary>Player layers</summary>
public const int Players = 9;
public const int PlayersMask = 1 << Players;
/// <summary>NPC layers</summary>
public const int NPCs = 10;
public const int NPCsMask = 1 << NPCs;
/// <summary>Guns, bullets objects layers</summary>
public const int GunObjects = 11;
public const int GunObjectsMask = 1 << GunObjects;
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/GlobalLayers.cs
|
C#
|
asf20
| 602
|
using System;
using System.Collections.Generic;
namespace GFramework
{
/// <summary>
/// Multimap
/// </summary>
/// <typeparam name="KeyType"></typeparam>
/// <typeparam name="ValueType"></typeparam>
public class SortedMultiMap<TKey, TValue> : IEnumerable<KeyValuePair<TKey, List<TValue>>>
{
SortedDictionary<TKey, List<TValue>> _dictionary;
public SortedMultiMap()
{
_dictionary = new SortedDictionary<TKey, List<TValue>>();
}
public SortedMultiMap(IComparer<TKey> comparer)
{
_dictionary = new SortedDictionary<TKey, List<TValue>>(comparer);
}
public void Add(TKey key, TValue value)
{
List<TValue> list;
if (this._dictionary.TryGetValue(key, out list))
{
list.Add(value);
}
else
{
list = new List<TValue>();
list.Add(value);
this._dictionary[key] = list;
}
}
public IEnumerable<TKey> Keys
{
get
{
return this._dictionary.Keys;
}
}
public IEnumerable<List<TValue>> Values
{
get
{
return this._dictionary.Values;
}
}
public List<TValue> this[TKey key]
{
get
{
List<TValue> list;
if (this._dictionary.TryGetValue(key, out list))
{
return list;
}
else
{
return new List<TValue>();
}
}
}
#region IEnumerable<KeyValuePair<TKey,List<TValue>>> Members
public IEnumerator<KeyValuePair<TKey, List<TValue>>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
/// <summary>
/// Multimap with priority
/// </summary>
/// <typeparam name="KeyType"></typeparam>
/// <typeparam name="ValueType"></typeparam>
public class MultiPriorityMap<TKey, TValue>
{
Dictionary<TKey, SortedMultiMap<int, TValue>> _dictionary;
public MultiPriorityMap()
{
_dictionary = new Dictionary<TKey, SortedMultiMap<int, TValue>>();
}
public MultiPriorityMap(IEqualityComparer<TKey> comparer)
{
_dictionary = new Dictionary<TKey, SortedMultiMap<int, TValue>>(comparer);
}
public void Add(TKey key, int priority, TValue value)
{
SortedMultiMap<int, TValue> priorityMap;
if (this._dictionary.TryGetValue(key, out priorityMap))
{
priorityMap.Add(priority, value);
}
else
{
priorityMap = new SortedMultiMap<int, TValue>();
priorityMap.Add(priority, value);
this._dictionary[key] = priorityMap;
}
}
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
public IEnumerable<TKey> Keys
{
get
{
return this._dictionary.Keys;
}
}
public SortedMultiMap<int, TValue> this[TKey key]
{
get
{
SortedMultiMap<int, TValue> priorityMap;
if (this._dictionary.TryGetValue(key, out priorityMap))
{
return priorityMap;
}
else
{
return new SortedMultiMap<int, TValue>();
}
}
}
public List<TValue> GetValueAsOrderedList(TKey key)
{
SortedMultiMap<int, TValue> priorityMap;
List<TValue> result = new List<TValue>();
if (this._dictionary.TryGetValue(key, out priorityMap))
{
foreach (KeyValuePair<int, List<TValue>> pair in priorityMap)
{
result.AddRange(pair.Value);
}
}
return result;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/MultiMap.cs
|
C#
|
asf20
| 3,503
|
using UnityEngine;
using System.Collections;
public class PickUtil {
public static bool PickObject(Camera camera, Vector2 screenPos, int layers, out RaycastHit hit)
{
Ray ray = camera.ScreenPointToRay(new Vector3(screenPos.x, screenPos.y, 0));
return Physics.Raycast(ray, out hit, layers);
}
public static GameObject PickObject(Camera camera, Vector2 screenPos, int layers)
{
RaycastHit hit;
if (!PickObject(camera, screenPos, layers, out hit))
return null;
return hit.collider.gameObject;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/PickUtil.cs
|
C#
|
asf20
| 532
|
using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
using GFramework;
[Serializable]
public class AlternativeMaterial
{
public string name;
public Material[] materials;
}
[AddComponentMenu("GFramework/Material Changer")]
public class MaterialChanger : MonoBehaviour
{
private Renderer _renderer;
// Multi materials
private Material[] originals;
private List<AlternativeMaterial> alternates;
void Awake()
{
_renderer = renderer;
}
public void ResetOriginal()
{
if (_renderer != null)
originals = _renderer.sharedMaterials;
}
public Material GetAlternate(string name)
{
return GetAlternate(name, null);
}
public Material GetAlternate(string name, string shader)
{
Material[] mats = GetAlternates(name, shader);
if (mats != null && mats.Length > 0)
return mats[0];
return null;
}
public Material[] GetAlternates(string name)
{
return GetAlternates(name, null);
}
public Material[] GetAlternates(string name, string shader)
{
if (_renderer == null)
return null;
if (alternates == null)
alternates = new List<AlternativeMaterial>();
if (originals == null)
originals = _renderer.sharedMaterials;
int found = alternates.FindIndex(m => m.name == name);
if (found >= 0)
return alternates[found].materials;
AlternativeMaterial amat = new AlternativeMaterial();
amat.name = name;
amat.materials = originals.Select(m =>
{
var mat = new Material(m);
mat.name = "# " + m.name;
if( !string.IsNullOrEmpty(shader) )
mat.shader = Shader.Find(shader);
return mat;
}).ToArray();
alternates.Add(amat);
return amat.materials;
}
public void CleanUp()
{
if (alternates != null)
{
foreach (var amat in alternates)
{
//Debug.LogError("Destroy " + amat.name);
if (amat.materials != null)
{
foreach (Material mat in amat.materials)
{
if (mat != null)
{
//Debug.LogError("Destroy 2 " + mat.name);
UnityEngine.Object.Destroy(mat);
}
}
}
}
alternates.Clear();
}
originals = null;
}
public void SetAlternate(string name)
{
SetAlternate(name, null);
}
public void SetAlternate(string name, string shader)
{
if (_renderer == null)
return;
renderer.sharedMaterial = GetAlternate(name, shader);
}
public void SetAlternates(string name)
{
SetAlternates(name, null);
}
public void SetAlternates(string name, string shader)
{
if (_renderer == null)
return;
renderer.sharedMaterials = GetAlternates(name, shader);
}
public bool CanChangeMaterial()
{
return _renderer != null && _renderer.sharedMaterial != null;
}
public static bool CanChangeMaterial(GameObject go)
{
Renderer rd = go.renderer;
return rd != null && rd.sharedMaterial != null;
}
void OnDestroy()
{
CleanUp();
}
public void RestoreMaterial()
{
if (_renderer == null || originals == null)
return;
renderer.sharedMaterials = originals;
}
//------------------------------------
// Doan nay can chinh sua lai
private Material[] temp = null;
public void ShowWall()
{
if (_renderer == null || originals == null)
return;
temp = renderer.sharedMaterials;
renderer.sharedMaterials = originals;
}
public void RestoreWall()
{
if (_renderer == null || originals == null)
return;
renderer.sharedMaterials = temp;
}
//------------------------------------
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/MaterialChanger.cs
|
C#
|
asf20
| 3,799
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace GFramework
{
public class OrderedListItem<TKey> where TKey : IComparable<TKey>
{
public TKey key;
public OrderedListItem()
{
}
public OrderedListItem(TKey key)
{
this.key = key;
}
}
public class OrderedList<TKey, TItem>
where TItem : OrderedListItem<TKey>, new()
where TKey : IComparable<TKey>
{
class ItemComparer : IComparer<TItem>
{
public int Compare(TItem x, TItem y)
{
return x.key.CompareTo(y.key);
}
}
private static ItemComparer comparer = new ItemComparer();
public static void Sort(List<TItem> list)
{
list.Sort(comparer);
}
public static int FindItemIndex(List<TItem> list, TKey key)
{
TItem item = new TItem();
item.key = key;
return list.BinarySearch(item, comparer);
}
public static void Add(List<TItem> list, TKey key, TItem item)
{
item.key = key;
list.Add(item);
list.Sort(comparer);
}
public static void AddIgnoreOrder(List<TItem> list, TKey key, TItem item)
{
item.key = key;
list.Add(item);
}
public static bool AddIfNotExisting(List<TItem> list, TKey key, TItem item)
{
int idx = FindItemIndex(list, key);
// Not found
if (idx < 0)
{
Add(list, key, item);
return true;
}
return false;
}
public static bool TryGetValue(List<TItem> list, TKey key, out TItem item)
{
int idx = FindItemIndex(list, key);
if (idx >= 0)
{
item = list[idx];
return true;
}
item = default(TItem);
return false;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/OrderedList.cs
|
C#
|
asf20
| 1,662
|
using System;
using System.Text;
using System.Globalization;
namespace GFramework
{
public class StringHelper
{
/// <summary>
/// To convert a byte Array of Unicode values (UTF-8 encoded) to a complete string.
/// </summary>
/// <param name="characters">Unicode byte Array to be converted to string</param>
/// <returns>string converted from Unicode byte Array</returns>
private static string Utf8ByteArrayToString(byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
string constructedstring = encoding.GetString(characters);
return (constructedstring);
}
/// <summary>
/// Converts the string to UTF8 byte array and is used in De serialization
/// </summary>
/// <param name="pXmlstring"></param>
/// <returns></returns>
private static byte[] StringToUtf8ByteArray(string pXmlstring)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlstring);
return byteArray;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Utilities/StringHelper.cs
|
C#
|
asf20
| 1,007
|
using UnityEngine;
using System.Collections;
using System;
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class SoundClipAttribute : Attribute {
public string name { get; set; }
public SoundClipAttribute(string name)
{
this.name = name;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Audio/SoundClipAttribute.cs
|
C#
|
asf20
| 301
|
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
[Serializable]
public class SoundName
{
public string name;
public AudioClip clip;
}
[ExecuteInEditMode]
[RequireComponent(typeof(AudioSource))]
public class SoundableObject : MonoBehaviour {
public List<SoundName> sounds;
public AudioSource _audio { get; private set; }
// One shot setting
public float oneShotCoolDown = 0.1f;
private float lastOneShotTime;
public int maxOneShotsPerSecond = 5;
private float lastOneShotCountTime;
private float lastOneShotCount;
void Awake()
{
if( sounds == null )
sounds = new List<SoundName>();
_audio = audio;
if (_audio == null)
{
_audio = gameObject.AddComponent<AudioSource>();
_audio.playOnAwake = false;
}
#if UNITY_EDITOR
foreach (var component in gameObject.GetComponents<Component>())
{
object[] attributes = component.GetType().GetCustomAttributes(true);
foreach (var attr in attributes)
{
if (attr is SoundClipAttribute == false)
continue;
string name = ((SoundClipAttribute) attr).name;
SoundName sound = sounds.Find(s => s.name == name);
if (sound == null)
{
sound = new SoundName();
sound.name = name;
sounds.Add(sound);
}
}
}
#endif
}
public AudioClip GetAudioClip(string name)
{
SoundName sound = sounds.Find(s => s.name == name);
if (sound == null)
return null;
return sound.clip;
}
/// <summary>
/// Play one shot with limit options
/// </summary>
/// <param name="name"></param>
/// <param name="ignorable"></param>
public void PlayOneShot(string name, bool ignorable)
{
float curTime = Time.realtimeSinceStartup;
if (ignorable)
{
if (curTime - lastOneShotTime < oneShotCoolDown )
return;
if ((int)lastOneShotCountTime == (int)curTime &&
lastOneShotCount >= maxOneShotsPerSecond)
return;
}
AudioClip clip = GetAudioClip(name);
if( clip == null ) return;
_audio.PlayOneShot(clip);
if ((int)lastOneShotCountTime == (int)curTime)
{
lastOneShotCount++;
}
else
{
lastOneShotCountTime = curTime;
lastOneShotCount = 1;
}
lastOneShotTime = curTime;
}
public void Play(string name)
{
_audio.loop = false;
_audio.clip = GetAudioClip(name);
_audio.Play();
}
public void PlayLoopSound(string name)
{
_audio.loop = true;
_audio.clip = GetAudioClip(name);
_audio.Play();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Audio/SoundableObject.cs
|
C#
|
asf20
| 2,534
|
using UnityEngine;
using System.Collections;
namespace Framework
{
//========================================================
// class BaseSingleton
//========================================================
// - for making singleton object
// - usage
// + declare class(derived )
// public class OnlyOne : BaseSingleton< OnlyOne >
// + client
// OnlyOne.Instance.[method]
//========================================================
public abstract class BaseSingleton<T> where T : new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
Debug.Log("New of " + typeof(T));
instance = new T();
}
return instance;
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Suga Framework/Base/BaseSingleton.cs
|
C#
|
asf20
| 765
|
using UnityEngine;
using System.Collections;
public class Bars : MonoBehaviour {
private float lastCutOffValue = 0f;
public float cutOffValue = 0;
private UITexture uiTexture = null;
private Material barMaterial = null;
// Use this for initialization
IEnumerator Start () {
uiTexture = GetComponent<UITexture>();
if(uiTexture == null || uiTexture.material == null)
{
Debug.LogWarning("Could not find UITexture or material");
enabled = false;
yield break;
}
//wait two frames so we know drawCall exists
yield return null; yield return null;
barMaterial = uiTexture.drawCall.dynamicMaterial;
}
// Update is called once per frame
void Update () {
if(barMaterial == null)
return;
if(cutOffValue < 0f)
cutOffValue = 0f;
else if(cutOffValue > 1f)
cutOffValue = 1f;
if(lastCutOffValue != cutOffValue)
{
lastCutOffValue = cutOffValue;
barMaterial.SetFloat("_Cutoff", cutOffValue);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/RPG Theme NGUI Skin/Script/Bars.cs
|
C#
|
asf20
| 954
|
/*
* MenuDemo.cs
* This script is for demonstration purposes only!
*/
using UnityEngine;
using System.Collections;
public class MenuDemo : MonoBehaviour {
//windows
GameObject inventoryWindow, questWindow, skillWindow, settingsWindow;
//tooltips
GameObject skillTooltip, itemTooltip, genericTooltip;
static string[] ToolTipableNames = { "ItemHP", "SkillItem", "SkillItemDisabled", "Stats" };
// Use this for initialization
void Start () {
//windows
inventoryWindow = GameObject.Find("InventoryWindow");
questWindow = GameObject.Find("QuestWindow");
skillWindow = GameObject.Find("SkillWindow");
settingsWindow = GameObject.Find("SettingsWindow");
//tooltips
skillTooltip = GameObject.Find("Tooltip Skill");
skillTooltip.SetActive(false);
itemTooltip = GameObject.Find("Tooltip Item");
itemTooltip.SetActive(false);
genericTooltip = GameObject.Find("Tooltip Generic");
genericTooltip.SetActive(false);
//add onClick handlers on the buttons
foreach (UIButton button in transform.GetComponentsInChildren<UIButton>())
{
UIEventListener.Get(button.gameObject).onClick += OnButtonClick;
}
//add onHover handlers on particular elements
foreach (string toolTipableName in ToolTipableNames)
{
foreach (Transform t in FindObjectsOfType(typeof(Transform)))
{
if (t.name.Contains(toolTipableName))
UIEventListener.Get(t.gameObject).onHover += OnHover;
}
}
//Hide windows
inventoryWindow.SetActive(false);
questWindow.SetActive(false);
skillWindow.SetActive(false);
settingsWindow.SetActive(false);
}
void OnHover(GameObject target, bool isOver)
{
switch (target.name)
{
case "SkillItemDisabled":
case "SkillItem":
skillTooltip.SetActive(isOver);
SetTooltipPos(target.transform.position, skillTooltip);
break;
case "ItemHP":
itemTooltip.SetActive(isOver);
SetTooltipPos(target.transform.position, itemTooltip);
break;
case "Stats":
genericTooltip.SetActive(isOver);
SetTooltipPos(target.transform.position, genericTooltip);
break;
}
}
void SetTooltipPos(Vector3 targetPos, GameObject tooltipWindow)
{
Vector3 newPos = targetPos;
Vector3 extends = tooltipWindow.collider.bounds.extents;
if(targetPos.x > 0)
newPos.x -= (extends.x + 0.1f); //offset of 0.1f
else
newPos.x += (extends.x + 0.1f); //offset of 0.1f
newPos.z = -0.1f; //always force the tooltip window to the front
tooltipWindow.transform.position = newPos;
}
void OnButtonClick(GameObject target)
{
switch (target.name)
{
case "BtnInventory":
inventoryWindow.SetActive(!inventoryWindow.activeInHierarchy);
break;
case "BtnQuest":
questWindow.SetActive(!questWindow.activeInHierarchy);
break;
case "BtnSkill":
skillWindow.SetActive(!skillWindow.activeInHierarchy);
break;
case "BtnSettings":
settingsWindow.SetActive(!settingsWindow.activeInHierarchy);
break;
case "BtnCloseInventory":
inventoryWindow.SetActive(false);
break;
case "BtnCloseQuest":
questWindow.SetActive(false);
break;
case "BtnDecline":
questWindow.SetActive(false);
break;
case "BtnAccept":
questWindow.SetActive(false);
break;
case "BtnCloseSkill":
skillWindow.SetActive(false);
break;
case "BtnCloseSettings":
settingsWindow.SetActive(false);
break;
case "BtnQuit":
settingsWindow.SetActive(false);
break;
default:
break;
}
}
// Update is called once per frame
void Update () {
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/RPG Theme NGUI Skin/Script/MenuDemo.cs
|
C#
|
asf20
| 4,597
|
Shader "HealthMagic"
{
Properties
{
_Color("Bar Color", Color) = (1,1,1,1)
_MainTex("Main Texture", 2D) = "black" {}
_Effect("Distortion Texture", 2D) = "black" {}
_Mask("Cutoff Mask", 2D) = "black" {}
_Distortion("Distortion Power", Float) = 0
_Offset("Distortion Offset", Float) = 0
_Speed("Scroll Speed", Float) = 0
_Cutoff("Bar Cutoff", Range(0,1.5) ) = 0.5
}
SubShader
{
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="False"
"RenderType"="Transparent"
}
Cull Back
ZWrite On
ZTest LEqual
ColorMask RGBA
Fog{
Mode Off
}
CGPROGRAM
#pragma surface surf BlinnPhongEditor noambient nolightmap alpha decal:blend vertex:vert
#pragma target 2.0
float4 _Color;
sampler2D _MainTex;
sampler2D _Effect;
sampler2D _Mask;
float _Distortion;
float _Offset;
float _Speed;
float _Cutoff;
struct EditorSurfaceOutput {
half3 Albedo;
half3 Normal;
half3 Emission;
half3 Gloss;
half Specular;
half Alpha;
half4 Custom;
};
inline half4 LightingBlinnPhongEditor_PrePass (EditorSurfaceOutput s, half4 light)
{
half3 spec = light.a * s.Gloss;
half4 c;
c.rgb = (s.Albedo * light.rgb + light.rgb * spec);
c.a = s.Alpha;
return c;
}
inline half4 LightingBlinnPhongEditor (EditorSurfaceOutput s, half3 lightDir, half3 viewDir, half atten)
{
half3 h = normalize (lightDir + viewDir);
half diff = max (0, dot ( lightDir, s.Normal ));
float nh = max (0, dot (s.Normal, h));
float spec = pow (nh, s.Specular*128.0);
half4 res;
res.rgb = _LightColor0.rgb * diff;
res.w = spec * Luminance (_LightColor0.rgb);
res *= atten * 2.0;
return LightingBlinnPhongEditor_PrePass( s, res );
}
struct Input {
float2 uv_Effect;
float2 uv_MainTex;
float4 color : COLOR;
float2 uv_Mask;
};
void vert (inout appdata_full v, out Input o) {
UNITY_INITIALIZE_OUTPUT(Input, o);
float4 VertexOutputMaster0_0_NoInput = float4(0,0,0,0);
float4 VertexOutputMaster0_1_NoInput = float4(0,0,0,0);
float4 VertexOutputMaster0_2_NoInput = float4(0,0,0,0);
float4 VertexOutputMaster0_3_NoInput = float4(0,0,0,0);
}
void surf (Input IN, inout EditorSurfaceOutput o) {
o.Normal = float3(0.0,0.0,1.0);
o.Alpha = 1.0;
o.Albedo = 0.0;
o.Emission = 0.0;
o.Gloss = 0.0;
o.Specular = 0.0;
o.Custom = 0.0;
float4 Split0=(IN.uv_Effect.xyxy);
float4 Multiply5=_Speed.xxxx * _Time;
float4 Add2=float4( Split0.x, Split0.x, Split0.x, Split0.x) + Multiply5;
float4 Assemble0=float4(Add2.x, float4( Split0.y, Split0.y, Split0.y, Split0.y).y, float4( Split0.z, Split0.z, Split0.z, Split0.z).z, float4( Split0.w, Split0.w, Split0.w, Split0.w).w);
float4 Floor0=floor(Assemble0);
float4 Subtract2=Assemble0 - Floor0;
float4 Tex2D3=tex2D(_Effect,Subtract2.xy);
float4 Multiply4=Tex2D3 * _Distortion.xxxx;
float4 Add1=(IN.uv_Effect.xyxy) + Multiply4;
float4 Multiply1=_Offset.xxxx * _Time;
float4 Subtract1=Add1 - Multiply1;
float4 Tex2D2=tex2D(_Effect,Subtract1.xy);
float4 Sampled2D0=tex2D(_MainTex,IN.uv_MainTex.xy);
float4 Add0=Tex2D2 + Sampled2D0;
float4 Multiply0=_Color * Add0;
float4 Multiply6=Multiply0 * IN.color;
float4 SplatAlpha0=IN.color.w;
float4 Sampled2D2=tex2D(_Mask,IN.uv_Mask.xy);
float4 Split1=Sampled2D2;
float4 Invert1= float4(1.0, 1.0, 1.0, 1.0) - float4( Split1.x, Split1.x, Split1.x, Split1.x);
float4 Subtract3=_Cutoff.xxxx - Invert1;
float4 Multiply3=Subtract3 * float4( 9,9,9,9 );
float4 Multiply2=Sampled2D0.aaaa * Multiply3;
float4 Multiply7=SplatAlpha0 * Multiply2;
float4 Master0_0_NoInput = float4(0,0,0,0);
float4 Master0_1_NoInput = float4(0,0,1,1);
float4 Master0_3_NoInput = float4(0,0,0,0);
float4 Master0_4_NoInput = float4(0,0,0,0);
float4 Master0_7_NoInput = float4(0,0,0,0);
float4 Master0_6_NoInput = float4(1,1,1,1);
o.Emission = Multiply6;
o.Alpha = Multiply7;
o.Normal = normalize(o.Normal);
}
ENDCG
}
Fallback "Diffuse"
}
|
zzzstrawhatzzz
|
trunk/client/Assets/RPG Theme NGUI Skin/Shader/HealthMagic.shader
|
ShaderLab
|
asf20
| 3,903
|
using UnityEngine;
using System.Collections;
/// <summary>
/// This tracks input gestures for a mouse device
/// </summary>
public class MouseGestures : FingerGestures
{
// Number of mouse buttons to track
public int maxMouseButtons = 3;
protected override void Start()
{
base.Start();
}
public override int MaxFingers
{
get { return maxMouseButtons; }
}
protected override FingerGestures.FingerPhase GetPhase( Finger finger )
{
int button = finger.Index;
// mouse button down?
if( Input.GetMouseButton( button ) )
{
// did we just press it?
if( Input.GetMouseButtonDown( button ) )
return FingerPhase.Began;
// find out if the mouse has moved since last update
Vector3 delta = GetPosition( finger ) - finger.Position;
if( delta.sqrMagnitude < 1.0f )
return FingerPhase.Stationary;
return FingerPhase.Moved;
}
// did we just release the button?
if( Input.GetMouseButtonUp( button ) )
return FingerPhase.Ended;
return FingerPhase.None;
}
protected override Vector2 GetPosition( Finger finger )
{
return Input.mousePosition;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/MouseGestures.cs
|
C#
|
asf20
| 1,351
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Input.Axis-based Pinch gesture replacement for mouse-device
/// Warning: it's a bit of a hack caused due to design limitations :(
/// </summary>
[AddComponentMenu( "FingerGestures/Gesture Recognizers/Mouse Pinch" )]
public class MousePinchGestureRecognizer : PinchGestureRecognizer
{
public string axis = "Mouse ScrollWheel";
int requiredFingers = 2;
protected override int GetRequiredFingerCount()
{
return requiredFingers;
}
protected override bool CanBegin( FingerGestures.IFingerList touches )
{
if( !CheckCanBeginDelegate( touches ) )
return false;
float motion = Input.GetAxis( axis );
if( Mathf.Abs( motion ) < 0.0001f )
return false;
return true;
}
protected override void OnBegin( FingerGestures.IFingerList touches )
{
StartPosition[0] = StartPosition[1] = Input.mousePosition;
Position[0] = Position[1] = Input.mousePosition;
delta = 0;
RaiseOnPinchBegin();
delta = DeltaScale * Input.GetAxis( axis );
resetTime = Time.time + 0.1f;
RaiseOnPinchMove();
}
float resetTime = 0;
protected override GestureState OnActive( FingerGestures.IFingerList touches )
{
float motion = Input.GetAxis( axis );
if( Mathf.Abs( motion ) < 0.001f )
{
if( resetTime <= Time.time )
{
RaiseOnPinchEnd();
return GestureState.Recognized;
}
return GestureState.InProgress;
}
else
{
resetTime = Time.time + 0.1f;
}
Position[0] = Position[1] = Input.mousePosition;
delta = DeltaScale * motion;
RaiseOnPinchMove();
return GestureState.InProgress;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/MousePinchGestureRecognizer.cs
|
C#
|
asf20
| 1,980
|
using UnityEngine;
using System.Collections;
/// <summary>
/// The finger motion detector component is not an actual gesture but is responsible for tracking the motion (or stillness) of a specific finger
/// </summary>
public class FingerMotionDetector : FGComponent
{
/// <summary>
/// Event fired when the finger started moving beyond the MoveThreshold.
/// Use AnchorPos corresponds to retrieve the last starting position
/// <see cref="AnchorPos"/>
/// <see cref="MoveThreshold"/>
/// </summary>
public event EventDelegate<FingerMotionDetector> OnMoveBegin;
/// <summary>
/// Event fired when the finger has moved since last update.
/// Use MoveDelta to retrieve the motion performed since last update
/// <see cref="MoveDelta"/>
/// </summary>
public event EventDelegate<FingerMotionDetector> OnMove;
/// <summary>
/// Event fired when the finger has stopped moving
/// </summary>
public event EventDelegate<FingerMotionDetector> OnMoveEnd;
/// <summary>
/// Event fired when the finger starts being stationary (not moving)
/// </summary>
public event EventDelegate<FingerMotionDetector> OnStationaryBegin;
/// <summary>
/// Event fired on each frame that the finger remains stationary.
/// Use ElapsedStationaryTime to retreive the amount of time elapsed since the finger started being stationary
/// <see cref="ElapsedStationaryTime"/>
/// </summary>
public event EventDelegate<FingerMotionDetector> OnStationary;
/// <summary>
/// Event fired when the finger stops being stationary (starts moving)
/// Use ElapsedStationaryTime to retreive the total amount of time the finger stayed stationary
/// <see cref="ElapsedStationaryTime"/>
/// </summary>
public event EventDelegate<FingerMotionDetector> OnStationaryEnd;
/// <summary>
/// Motion state
/// </summary>
public enum MotionState
{
/// <summary>
/// Undefined
/// </summary>
None,
/// <summary>
/// The finger is not moving
/// </summary>
Stationary,
/// <summary>
/// The finger is moving
/// </summary>
Moving,
}
/// <summary>
/// Tolerance distance the finger is allowed to move from its initial position
/// without being recognized as an actual motion
/// </summary>
public float MoveThreshold = 5.0f;
FingerGestures.Finger finger;
MotionState state = MotionState.None;
MotionState prevState = MotionState.None;
int moves = 0;
float stationaryStartTime = 0;
Vector2 anchorPos = Vector2.zero;
bool wasDown = false; // this tracks if the finger was down in our previous update
/// <summary>
/// Get or set the finger to track
/// </summary>
public virtual FingerGestures.Finger Finger
{
get { return finger; }
set { finger = value; }
}
/// <summary>
/// Current finger motion state
/// </summary>
protected MotionState State
{
get { return state; }
private set
{
state = value;
}
}
/// <summary>
/// Finger motion state during the previous update
/// </summary>
protected MotionState PreviousState
{
get { return prevState; }
private set { prevState = value; }
}
/// <summary>
/// Number of moves performed
/// A complete MoveBegin/Move/MoveEnd sequence counts for 1 move.
/// </summary>
public int Moves
{
get { return moves; }
private set { moves = value; }
}
/// <summary>
/// Return true if at least one finger move was performed (see Moves property above)
/// </summary>
public bool Moved
{
get { return Moves > 0; }
}
/// <summary>
/// Return true if Moving was true during the previous update
/// </summary>
public bool WasMoving
{
get { return PreviousState == MotionState.Moving; }
}
/// <summary>
/// Is the finger currently moving this frame?
/// </summary>
public bool Moving
{
get { return State == MotionState.Moving; }
}
/// <summary>
/// Amount of time spent during the last or current stationary state sequence
/// from OnBeginStationary up to OnEndStationary.
/// </summary>
public float ElapsedStationaryTime
{
get { return Time.time - stationaryStartTime; }
}
/// <summary>
/// Reference position used to evaluate if we're still within the move threshold distance.
/// This is the last initial stationary position (initial finger contact position, or
/// finger position during the last OnMoveEnd event)
/// </summary>
public Vector2 AnchorPos
{
get { return anchorPos; }
private set { anchorPos = value; }
}
protected override void OnUpdate( FingerGestures.IFingerList touches )
{
if( Finger.IsDown )
{
if( !wasDown )
{
Moves = 0;
AnchorPos = Finger.Position;
State = MotionState.Stationary;
}
if( Finger.Phase == FingerGestures.FingerPhase.Moved )
{
if( State != MotionState.Moving )
{
Vector2 delta = Finger.Position - AnchorPos;
// check if we moved beyond the threshold
if( delta.sqrMagnitude >= MoveThreshold * MoveThreshold )
State = MotionState.Moving;
else
State = MotionState.Stationary;
}
}
else
{
State = MotionState.Stationary;
}
}
else
{
State = MotionState.None;
}
RaiseEvents();
PreviousState = State;
wasDown = Finger.IsDown;
}
void RaiseEvents()
{
// state transition
if( State != PreviousState )
{
// end previous state
if( PreviousState == MotionState.Moving )
{
RaiseOnMoveEnd();
AnchorPos = Finger.Position;
}
else if( PreviousState == MotionState.Stationary )
{
RaiseOnStationaryEnd();
}
// begin new state
if( State == MotionState.Moving )
{
RaiseOnMoveBegin();
++Moves;
}
else if( State == MotionState.Stationary )
{
stationaryStartTime = Time.time;
RaiseOnStationaryBegin();
}
}
if( State == MotionState.Stationary )
{
RaiseOnStationary();
}
else if( State == MotionState.Moving )
{
RaiseOnMove();
}
}
#region Event firing wrappers
protected void RaiseOnMoveBegin()
{
if( OnMoveBegin != null )
OnMoveBegin( this );
}
protected void RaiseOnMove()
{
if( OnMove != null )
OnMove( this );
}
protected void RaiseOnMoveEnd()
{
if( OnMoveEnd != null )
OnMoveEnd( this );
}
protected void RaiseOnStationaryBegin()
{
if( OnStationaryBegin != null )
OnStationaryBegin( this );
}
protected void RaiseOnStationary()
{
if( OnStationary != null )
OnStationary( this );
}
protected void RaiseOnStationaryEnd()
{
if( OnStationaryEnd != null )
OnStationaryEnd( this );
}
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/FingerMotionDetector.cs
|
C#
|
asf20
| 8,020
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Swipe gesture: quick drag/drop motion & release in a cardinal direction (e.g. a page flip with the finger)
/// </summary>
[AddComponentMenu( "FingerGestures/Gesture Recognizers/Swipe" )]
public class SwipeGestureRecognizer : AveragedGestureRecognizer
{
/// <summary>
/// Event fired when a valid swipe gesture has been detected, upon release of the finger(s)
/// <see cref="Direction"/>
/// <see cref="Velocity"/>
/// </summary>
public event EventDelegate<SwipeGestureRecognizer> OnSwipe;
/// <summary>
/// Directions we want the swipe recognizer to detect
/// </summary>
public FingerGestures.SwipeDirection ValidDirections = FingerGestures.SwipeDirection.All;
/// <summary>
/// Minimum swipe distance
/// </summary>
public float MinDistance = 1.0f;
/// <summary>
/// Minimum swipe velocity
/// </summary>
public float MinVelocity = 1.0f;
/// <summary>
/// Amount of tolerance when determining if the finger motion was performed along one of the supported swipe directions.
/// This amount should be kept between 0 and 0.5f, where 0 means no tolerance and 0.5f means you can move within 45 degrees away from the allowed direction
/// </summary>
public float DirectionTolerance = 0.2f; //DOT
Vector2 move;
FingerGestures.SwipeDirection direction = FingerGestures.SwipeDirection.None;
float velocity = 0;
float startTime = 0;
/// <summary>
/// Get the total move from start position to last/current position
/// </summary>
public Vector2 Move
{
get { return move; }
private set { move = value; }
}
/// <summary>
/// Get the swipe direction detected
/// </summary>
public FingerGestures.SwipeDirection Direction
{
get { return direction; }
}
/// <summary>
/// Get the current swipe velocity (in screen units per second)
/// </summary>
public float Velocity
{
get { return velocity; }
}
/// <summary>
/// Return true if the input direction is supported
/// </summary>
public bool IsValidDirection( FingerGestures.SwipeDirection dir )
{
if( dir == FingerGestures.SwipeDirection.None )
return false;
return ( ( ValidDirections & dir ) == dir );
}
protected override bool CanBegin( FingerGestures.IFingerList touches )
{
if( !base.CanBegin( touches ) )
return false;
if( touches.GetAverageDistanceFromStart() < 0.5f )
return false;
return true;
}
protected override void OnBegin( FingerGestures.IFingerList touches )
{
Position = touches.GetAveragePosition();
StartPosition = Position;
direction = FingerGestures.SwipeDirection.None;
startTime = Time.time;
}
protected override GestureState OnActive( FingerGestures.IFingerList touches )
{
if( touches.Count != RequiredFingerCount )
{
// fingers were lifted off
if( touches.Count < RequiredFingerCount )
{
if( direction != FingerGestures.SwipeDirection.None )
{
if( OnSwipe != null )
OnSwipe( this );
return GestureState.Recognized;
}
}
return GestureState.Failed;
}
Position = touches.GetAveragePosition();
Move = Position - StartPosition;
float distance = Move.magnitude;
// didnt move far enough
if( distance < MinDistance )
return GestureState.InProgress;
float elapsedTime = Time.time - startTime;
if( elapsedTime > 0 )
velocity = distance / elapsedTime;
else
velocity = 0;
// we're going too slow
if( velocity < MinVelocity )
return GestureState.Failed;
FingerGestures.SwipeDirection newDirection = FingerGestures.GetSwipeDirection( Move.normalized, DirectionTolerance );
// we went in a bad direction
if( !IsValidDirection( newDirection ) || ( direction != FingerGestures.SwipeDirection.None && newDirection != direction ) )
return GestureState.Failed;
direction = newDirection;
return GestureState.InProgress;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/SwipeGestureRecognizer.cs
|
C#
|
asf20
| 4,588
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Rotation gesture, also known as twist gesture
/// This gesture is performed by moving two fingers around a point of reference in opposite directions
///
/// NOTE: it is recommanded to set ResetMode to GestureResetMode.NextFrame for this gesture
/// </summary>
[AddComponentMenu( "FingerGestures/Gesture Recognizers/Rotation" )]
public class RotationGestureRecognizer : MultiFingerGestureRecognizer
{
/// <summary>
/// Event fired when the rotation gesture starts
/// <see cref="MinRotation"/>
/// <see cref="MinDOT"/>
/// </summary>
public event EventDelegate<RotationGestureRecognizer> OnRotationBegin;
/// <summary>
/// Event fired when the rotation angle has changed.
/// Query RotationDelta to get the angle difference since last frame
/// Query TotalRotation to get the total angular motion since the beginning of the gesture
/// <see cref="RotationDelta"/>
/// <see cref="TotalRotation"/>
/// </summary>
public event EventDelegate<RotationGestureRecognizer> OnRotationMove;
/// <summary>
/// Event fired when the rotation gesture is finished
/// <see cref="TotalRotation"/>
/// </summary>
public event EventDelegate<RotationGestureRecognizer> OnRotationEnd;
/// <summary>
/// Rotation DOT product treshold - this controls how tolerant the twist gesture detector is to the two fingers
/// moving in opposite directions.
/// Setting this to -1 means the fingers have to move in exactly opposite directions to each other.
/// this value should be kept between -1 and 0 excluded.
/// </summary>
public float MinDOT = -0.7f;
/// <summary>
/// Minimum amount of rotation required to start the rotation gesture (in degrees)
/// </summary>
public float MinRotation = 1.0f;
float totalRotation = 0.0f;
float rotationDelta = 0.0f;
/// <summary>
/// Get total rotation angle since gesture started (in degrees)
/// </summary>
public float TotalRotation
{
get { return totalRotation; }
}
/// <summary>
/// Get rotation angle change since last move (in degrees)
/// </summary>
public float RotationDelta
{
get { return rotationDelta; }
}
#region Utils
bool FingersMovedInOppositeDirections( FingerGestures.Finger finger0, FingerGestures.Finger finger1 )
{
return FingerGestures.FingersMovedInOppositeDirections( finger0, finger1, MinDOT );
}
// return signed angle in degrees between current finger position and ref positions
static float SignedAngularGap( FingerGestures.Finger finger0, FingerGestures.Finger finger1, Vector2 refPos0, Vector2 refPos1 )
{
Vector2 curDir = ( finger0.Position - finger1.Position ).normalized;
Vector2 refDir = ( refPos0 - refPos1 ).normalized;
// check if we went past the minimum rotation amount treshold
return Mathf.Rad2Deg * FingerGestures.SignedAngle( refDir, curDir );
}
#endregion
protected override int GetRequiredFingerCount() { return 2; }
protected override bool CanBegin( FingerGestures.IFingerList touches )
{
if( !base.CanBegin( touches ) )
return false;
FingerGestures.Finger finger0 = touches[0];
FingerGestures.Finger finger1 = touches[1];
if( !FingerGestures.AllFingersMoving( finger0, finger1 ) )
return false;
if( !FingersMovedInOppositeDirections( finger0, finger1 ) )
return false;
// check if we went past the minimum rotation amount treshold
float rotation = SignedAngularGap( finger0, finger1, finger0.StartPosition, finger1.StartPosition );
if( Mathf.Abs( rotation ) < MinRotation )
return false;
return true;
}
protected override void OnBegin( FingerGestures.IFingerList touches )
{
FingerGestures.Finger finger0 = touches[0];
FingerGestures.Finger finger1 = touches[1];
StartPosition[0] = finger0.StartPosition;
StartPosition[1] = finger1.StartPosition;
Position[0] = finger0.Position;
Position[1] = finger1.Position;
float angle = SignedAngularGap( finger0, finger1, finger0.StartPosition, finger1.StartPosition );
totalRotation = Mathf.Sign( angle ) * MinRotation;
rotationDelta = 0;
if( OnRotationBegin != null )
OnRotationBegin( this );
rotationDelta = angle - totalRotation;
totalRotation = angle;
if( OnRotationMove != null )
OnRotationMove( this );
}
protected override GestureState OnActive( FingerGestures.IFingerList touches )
{
if( touches.Count != RequiredFingerCount )
{
// fingers were lifted?
if( touches.Count < RequiredFingerCount )
{
if( OnRotationEnd != null )
OnRotationEnd( this );
return GestureState.Recognized;
}
// more fingers added, gesture failed
return GestureState.Failed;
}
FingerGestures.Finger finger0 = touches[0];
FingerGestures.Finger finger1 = touches[1];
Position[0] = finger0.Position;
Position[1] = finger1.Position;
// dont do anything if both fingers arent moving
if( !FingerGestures.AllFingersMoving( finger0, finger1 ) )
return GestureState.InProgress;
rotationDelta = SignedAngularGap( finger0, finger1, finger0.PreviousPosition, finger1.PreviousPosition );
totalRotation += rotationDelta;
if( OnRotationMove != null )
OnRotationMove( this );
return GestureState.InProgress;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/RotationGestureRecognizer.cs
|
C#
|
asf20
| 5,956
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Long-Press gesture: detects when the finger is held down without moving, for a specific duration
/// </summary>
[AddComponentMenu( "FingerGestures/Gesture Recognizers/Long Press" )]
public class LongPressGestureRecognizer : AveragedGestureRecognizer
{
/// <summary>
/// Event fired when the the gesture is recognized
/// </summary>
public event EventDelegate<LongPressGestureRecognizer> OnLongPress;
/// <summary>
/// How long the finger must stay down without moving in order to validate the gesture
/// </summary>
public float Duration = 1.0f;
/// <summary>
/// How far the finger is allowed to move around its starting position without breaking the gesture
/// </summary>
public float MoveTolerance = 5.0f;
float startTime = 0;
/// <summary>
/// Time when the gesture last started
/// </summary>
public float StartTime
{
get { return startTime; }
}
protected override void OnBegin( FingerGestures.IFingerList touches )
{
Position = touches.GetAveragePosition();
StartPosition = Position;
startTime = Time.time;
}
protected override GestureState OnActive( FingerGestures.IFingerList touches )
{
if( touches.Count != RequiredFingerCount )
return GestureState.Failed;
float elapsedTime = Time.time - startTime;
if( elapsedTime >= Duration )
{
RaiseOnLongPress();
return GestureState.Recognized;
}
// check if we moved too far from initial position
if( touches.GetAverageDistanceFromStart() > MoveTolerance )
return GestureState.Failed;
return GestureState.InProgress;
}
protected void RaiseOnLongPress()
{
if( OnLongPress != null )
OnLongPress( this );
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/LongPressGestureRecognizer.cs
|
C#
|
asf20
| 1,977
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Tap gesture: single or multiple consecutive press and release gestures at the same location
/// </summary>
[AddComponentMenu( "FingerGestures/Gesture Recognizers/Tap" )]
public class TapGestureRecognizer : AveragedGestureRecognizer
{
/// <summary>
/// Event fired when a tap occurs (if RequiredTaps is 0) or when the exact number of RequiredTaps has been reached
/// </summary>
public event EventDelegate<TapGestureRecognizer> OnTap;
/// <summary>
/// Exact number of taps required to succesfully recognize the tap gesture.
/// If RequiredTaps is set to a positive value, the gesture recognizer will reset once the number of consecutive taps performed is equal to
/// this value.
/// </summary>
/// <seealso cref="Taps"/>
public int RequiredTaps = 0;
/// <summary>
/// When set to true, the OnTap event will fire each time a tap occurs.
/// When set to false, the OnTap event will only be fired on the last tap produced (either by time-out or when reaching the RequiredTaps count)
/// </summary>
/// <seealso cref="RequiredTaps"/>
public bool RaiseEventOnEachTap = false;
/// <summary>
/// The maximum amount of the time that can elapse between two consecutive taps without causing the recognizer to reset.
/// Set to 0 to ignore this setting.
/// </summary>
public float MaxDelayBetweenTaps = 0.25f;
/// <summary>
/// The maximum total duration of a tap sequence, in seconds. The tap recognizer automatically resets after this duration.
/// Set to 0 to ignore this setting.
/// </summary>
public float MaxDuration = 0.0f;
/// <summary>
/// How far the finger can move from its initial position without making the gesture fail
/// </summary>
public float MoveTolerance = 5.0f;
int taps = 0;
bool down = false;
bool wasDown = false;
float lastDownTime = 0;
float lastTapTime = 0;
float startTime = 0;
/// <summary>
/// Get the current number of consecutive taps achieved
/// </summary>
public int Taps
{
get { return taps; }
}
bool MovedTooFar( Vector2 curPos )
{
Vector2 delta = curPos - StartPosition;
return delta.sqrMagnitude >= ( MoveTolerance * MoveTolerance );
}
bool HasTimedOut()
{
// check elapsed time since last tap
if( MaxDelayBetweenTaps > 0 && ( Time.time - lastTapTime > MaxDelayBetweenTaps ) )
return true;
// check elapsed time since beginning of gesture
if( MaxDuration > 0 && ( Time.time - startTime > MaxDuration ) )
return true;
return false;
}
protected override void Reset()
{
taps = 0;
down = false;
wasDown = false;
base.Reset();
}
protected override void OnBegin( FingerGestures.IFingerList touches )
{
Position = touches.GetAveragePosition();
StartPosition = Position;
lastTapTime = Time.time;
startTime = Time.time;
}
protected override GestureState OnActive( FingerGestures.IFingerList touches )
{
wasDown = down;
down = false;
if( touches.Count == RequiredFingerCount )
{
down = true;
lastDownTime = Time.time;
}
else if( touches.Count == 0 )
{
down = false;
}
else
{
// some fingers were lifted off
if( touches.Count < RequiredFingerCount )
{
// give a bit of buffer time to lift-off the remaining fingers
if( Time.time - lastDownTime > 0.25f )
return GestureState.Failed;
}
else // fingers were added
{
return GestureState.Failed;
}
}
if( HasTimedOut() )
{
// if we requested unlimited taps and landed at least one, consider this a success
if( RequiredTaps == 0 && Taps > 0 )
{
// if we didn't raise a tap event on each tap, at least raise the event once at the end of the tap sequence
if( !RaiseEventOnEachTap )
RaiseOnTap();
return GestureState.Recognized;
}
// else, timed out
return GestureState.Failed;
}
if( down )
{
Vector2 curPos = touches.GetAveragePosition();
// check if finger moved too far from start position
if( MovedTooFar( curPos ) )
return GestureState.Failed;
}
if( wasDown != down )
{
// fingers were just released
if( !down )
{
++taps;
lastTapTime = Time.time;
// If the requested tap count has been reached, validate the gesture and stop
if( RequiredTaps > 0 && taps >= RequiredTaps )
{
RaiseOnTap();
return GestureState.Recognized;
}
if( RaiseEventOnEachTap )
RaiseOnTap();
}
}
return GestureState.InProgress;
}
protected void RaiseOnTap()
{
if( OnTap != null )
OnTap( this );
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/TapGestureRecognizer.cs
|
C#
|
asf20
| 5,597
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Pinch gesture: two fingers moving closer or further away from each other
///
/// NOTE: it is recommanded to set ResetMode to GestureResetMode.NextFrame for this gesture
/// </summary>
[AddComponentMenu( "FingerGestures/Gesture Recognizers/Pinch" )]
public class PinchGestureRecognizer : MultiFingerGestureRecognizer
{
/// <summary>
/// Event fired when the
/// </summary>
public event EventDelegate<PinchGestureRecognizer> OnPinchBegin;
/// <summary>
/// Event fired when the distance between the two fingers has changed
/// <see cref="Delta"/>
/// </summary>
public event EventDelegate<PinchGestureRecognizer> OnPinchMove;
/// <summary>
/// Event fired when the gesture has ended (e.g. at least one of the fingers was lifted off)
/// </summary>
public event EventDelegate<PinchGestureRecognizer> OnPinchEnd;
/// <summary>
/// Pinch DOT product treshold - this controls how tolerant the pinch gesture detector is to the two fingers
/// moving in opposite directions.
/// Setting this to -1 means the fingers have to move in exactly opposite directions to each other.
/// this value should be kept between -1 and 0 excluded.
/// </summary>
public float MinDOT = -0.7f;
/// <summary>
/// Minimum pinch distance required to trigger the pinch gesture
/// </summary>
public float MinDistance = 5.0f;
/// <summary>
/// How much to scale the internal pinch delta by before raising the OnPinchMove event
/// </summary>
public float DeltaScale = 1.0f;
protected float delta = 0.0f;
/// <summary>
/// Signed change in distance between the two fingers since last update
/// A negative value means the two fingers got closer, while a positive value means they moved further apart
/// </summary>
public float Delta
{
get { return delta; }
}
// Only support 2 simultaneous fingers right now
protected override int GetRequiredFingerCount()
{
return 2;
}
protected override bool CanBegin( FingerGestures.IFingerList touches )
{
if( !base.CanBegin( touches ) )
return false;
FingerGestures.Finger finger0 = touches[0];
FingerGestures.Finger finger1 = touches[1];
if( !FingerGestures.AllFingersMoving( finger0, finger1 ) )
return false;
if( !FingersMovedInOppositeDirections( finger0, finger1 ) )
return false;
float gapDelta = ComputeGapDelta( finger0, finger1, finger0.StartPosition, finger1.StartPosition );
if( Mathf.Abs( gapDelta ) < MinDistance )
return false;
return true;
}
protected override void OnBegin( FingerGestures.IFingerList touches )
{
FingerGestures.Finger finger0 = touches[0];
FingerGestures.Finger finger1 = touches[1];
StartPosition[0] = finger0.StartPosition;
StartPosition[1] = finger1.StartPosition;
Position[0] = finger0.Position;
Position[1] = finger1.Position;
RaiseOnPinchBegin();
float startDelta = ComputeGapDelta( finger0, finger1, finger0.StartPosition, finger1.StartPosition );
delta = DeltaScale * ( startDelta - Mathf.Sign( startDelta ) * MinDistance );
RaiseOnPinchMove();
}
protected override GestureState OnActive( FingerGestures.IFingerList touches )
{
if( touches.Count != RequiredFingerCount )
{
// fingers were lifted?
if( touches.Count < RequiredFingerCount )
{
RaiseOnPinchEnd();
return GestureState.Recognized;
}
// more fingers added, gesture failed
return GestureState.Failed;
}
FingerGestures.Finger finger0 = touches[0];
FingerGestures.Finger finger1 = touches[1];
Position[0] = finger0.Position;
Position[1] = finger1.Position;
// dont do anything if both fingers arent moving
if( !FingerGestures.AllFingersMoving( finger0, finger1 ) )
return GestureState.InProgress;
float newDelta = ComputeGapDelta( finger0, finger1, finger0.PreviousPosition, finger1.PreviousPosition );
if( Mathf.Abs( newDelta ) > 0.001f )
{
if( !FingersMovedInOppositeDirections( finger0, finger1 ) )
return GestureState.InProgress; //TODO: might want to make this configurable, so the recognizer can fail if fingers move in same direction
delta = DeltaScale * newDelta;
RaiseOnPinchMove();
}
return GestureState.InProgress;
}
#region Event-Raising Wrappers
protected void RaiseOnPinchBegin()
{
if( OnPinchBegin != null )
OnPinchBegin( this );
}
protected void RaiseOnPinchMove()
{
if( OnPinchMove != null )
OnPinchMove( this );
}
protected void RaiseOnPinchEnd()
{
if( OnPinchEnd != null )
OnPinchEnd( this );
}
#endregion
#region Utils
bool FingersMovedInOppositeDirections( FingerGestures.Finger finger0, FingerGestures.Finger finger1 )
{
return FingerGestures.FingersMovedInOppositeDirections( finger0, finger1, MinDOT );
}
float ComputeGapDelta( FingerGestures.Finger finger0, FingerGestures.Finger finger1, Vector2 refPos1, Vector2 refPos2 )
{
Vector2 curDelta = finger0.Position - finger1.Position;
Vector2 refDelta = refPos1 - refPos2;
return curDelta.magnitude - refDelta.magnitude;
}
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/PinchGestureRecognizer.cs
|
C#
|
asf20
| 5,866
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Drag gesture: a full finger press > move > release sequence
/// </summary>
[AddComponentMenu( "FingerGestures/Gesture Recognizers/Drag" )]
public class DragGestureRecognizer : AveragedGestureRecognizer
{
/// <summary>
/// Event fired when the finger moved past its MoveTolerance radius from the StartPosition
/// <see cref="MoveTolerance"/>
/// <see cref="StartPosition"/>
/// </summary>
public event EventDelegate<DragGestureRecognizer> OnDragBegin;
/// <summary>
/// Event fired when the finger moved since the last update
/// Use MoveDelta to retrieve the amount of motion performed since last update
/// <see cref="MoveDelta"/>
/// </summary>
public event EventDelegate<DragGestureRecognizer> OnDragMove;
/// <summary>
/// Event fired when the dragged finger is released
/// </summary>
public event EventDelegate<DragGestureRecognizer> OnDragEnd;
/// <summary>
/// How far the finger is allowed to move from its initial position without making the gesture fail
/// </summary>
public float MoveTolerance = 5.0f;
Vector2 delta = Vector2.zero;
Vector2 lastPos = Vector2.zero;
/// <summary>
/// Amount of motion performed since the last update
/// </summary>
public Vector2 MoveDelta
{
get { return delta; }
private set { delta = value; }
}
protected override bool CanBegin( FingerGestures.IFingerList touches )
{
if( !base.CanBegin( touches ) )
return false;
if( touches.GetAverageDistanceFromStart() < MoveTolerance )
return false;
return true;
}
protected override void OnBegin( FingerGestures.IFingerList touches )
{
Position = touches.GetAveragePosition();
StartPosition = Position;
MoveDelta = Vector2.zero;
lastPos = Position;
RaiseOnDragBegin();
}
protected override GestureState OnActive( FingerGestures.IFingerList touches )
{
if( touches.Count != RequiredFingerCount )
{
// fingers were lifted off
if( touches.Count < RequiredFingerCount )
{
RaiseOnDragEnd();
return GestureState.Recognized;
}
return GestureState.Failed;
}
Position = touches.GetAveragePosition();
MoveDelta = Position - lastPos;
if( MoveDelta.sqrMagnitude > 0 )
{
RaiseOnDragMove();
lastPos = Position;
}
return GestureState.InProgress;
}
#region Event-Raising Wrappers
protected void RaiseOnDragBegin()
{
if( OnDragBegin != null )
OnDragBegin( this );
}
protected void RaiseOnDragMove()
{
if( OnDragMove != null )
OnDragMove( this );
}
protected void RaiseOnDragEnd()
{
if( OnDragEnd != null )
OnDragEnd( this );
}
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/DragGestureRecognizer.cs
|
C#
|
asf20
| 3,164
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Base class for any FingerGestures component
/// Its main task is to fire off OnUpdate() after the FingerGestures.Fingers have been updated during this frame.
/// </summary>
public abstract class FGComponent : MonoBehaviour
{
public delegate void EventDelegate<T>( T source ) where T : FGComponent;
protected virtual void Awake()
{
// made virtual in case of furture usage
}
protected virtual void Start()
{
// made virtual in case of furture usage
}
protected virtual void OnEnable()
{
FingerGestures.OnFingersUpdated += FingerGestures_OnFingersUpdated;
}
protected virtual void OnDisable()
{
FingerGestures.OnFingersUpdated -= FingerGestures_OnFingersUpdated;
}
void FingerGestures_OnFingersUpdated()
{
OnUpdate( FingerGestures.Touches );
}
/// <summary>
/// This is called after FingerGestures has updated the state of each finger
/// </summary>
/// <param name="touches">The list of fingers currently down / touching the screen</param>
protected abstract void OnUpdate( FingerGestures.IFingerList touches );
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/Base/FGComponent.cs
|
C#
|
asf20
| 1,247
|
using UnityEngine;
using System.Collections;
/// <summary>
/// The base class for all gesture recognizers
/// </summary>
public abstract class GestureRecognizer : FGComponent
{
/// <summary>
/// Possible gesture states
/// </summary>
public enum GestureState
{
/// <summary>
/// The gesture recognizer is ready and waiting for the correct initial input conditions to begin
/// </summary>
Ready,
/// <summary>
/// The gesture recognition has started and is still going on
/// </summary>
InProgress,
/// <summary>
/// The gesture detected a user input that invalidated it
/// </summary>
Failed,
/// <summary>
/// The gesture was succesfully recognized
/// </summary>
Recognized,
}
/// <summary>
/// The reset mode determines when to reset a GestureRecognizer after it fails or succeed (GestureState.Failed or GestureState.Recognized)
/// </summary>
public enum GestureResetMode
{
/// <summary>
/// The gesture recognizer will reset on the next Update()
/// </summary>
NextFrame,
/// <summary>
/// The gesture recognizer will reset at the end of the current multitouch sequence
/// </summary>
EndOfTouchSequence,
/// <summary>
/// The gesture recognizer will reset at the beginning of the next multitouch sequence
/// </summary>
StartOfTouchSequence,
}
#region State
/// <summary>
/// Event fired whenever the gesture recognizer state changes
/// <see cref="State"/>
/// <see cref="PreviousState"/>
/// </summary>
public event EventDelegate<GestureRecognizer> OnStateChanged;
GestureState prevState = GestureState.Ready;
GestureState state = GestureState.Ready;
/// <summary>
/// Get the previous gesture state
/// </summary>
public GestureState PreviousState
{
get { return prevState; }
}
/// <summary>
/// Get or set the current gesture state
/// </summary>
public GestureState State
{
get { return state; }
protected set
{
if( state != value )
{
prevState = state;
state = value;
if( OnStateChanged != null )
OnStateChanged( this );
}
}
}
/// <summary>
/// Return true if the gesture recognition has started and is on-going
/// <see cref="State"/>
/// </summary>
public bool IsActive
{
get { return State == GestureState.InProgress; }
}
#endregion
#region Reset
/// <summary>
/// Get or set the reset mode for this gesture recognizer
/// </summary>
public GestureResetMode ResetMode = GestureResetMode.StartOfTouchSequence;
/// <summary>
/// Put back the gesture recognizer in Ready state and reset any relevant data
/// <see cref="ResetMode"/>
/// </summary>
protected virtual void Reset()
{
State = GestureState.Ready;
}
#endregion
protected override void Start()
{
base.Start();
Reset();
}
#region Touch Sequence
/// <summary>
/// Called when the first finger of a new multi-touch sequence has touched the screen
/// </summary>
protected virtual void OnTouchSequenceStarted()
{
if( ResetMode == GestureResetMode.StartOfTouchSequence )
{
if( State == GestureState.Recognized || State == GestureState.Failed )
Reset();
}
}
/// <summary>
/// Called when all the fingers that participated in the current multi-touch sequence are no longer touching the screen
/// </summary>
protected virtual void OnTouchSequenceEnded()
{
if( ResetMode == GestureResetMode.EndOfTouchSequence )
{
if( State == GestureState.Recognized || State == GestureState.Failed )
Reset();
}
}
#endregion
int lastTouchesCount = 0;
protected override void OnUpdate( FingerGestures.IFingerList touches )
{
if( touchFilter != null )
touches = touchFilter.Apply( touches );
if( touches.Count > 0 && lastTouchesCount == 0 )
OnTouchSequenceStarted();
switch( State )
{
case GestureState.Recognized:
case GestureState.Failed:
if( ResetMode == GestureResetMode.NextFrame )
Reset();
break;
case GestureState.Ready:
State = OnReady( touches );
break;
case GestureState.InProgress:
State = OnActive( touches );
break;
default:
Debug.LogError( this + " - Unhandled state: " + State + ". Failing recognizer." );
State = GestureState.Failed;
break;
}
if( touches.Count == 0 && lastTouchesCount > 0 )
OnTouchSequenceEnded();
lastTouchesCount = touches.Count;
}
protected virtual GestureState OnReady( FingerGestures.IFingerList touches )
{
if( ShouldFailFromReady( touches ) )
return GestureState.Failed;
if( CanBegin( touches ) )
{
OnBegin( touches );
return GestureState.InProgress;
}
return GestureState.Ready;
}
protected virtual bool ShouldFailFromReady( FingerGestures.IFingerList touches )
{
if( touches.Count != GetRequiredFingerCount() )
{
if( touches.Count > 0 && !Young( touches ) )
return true;
}
return false;
}
/// <summary>
/// This controls whether or not the gesture recognition should begin
/// </summary>
/// <param name="touches">The active touches</param>
protected virtual bool CanBegin( FingerGestures.IFingerList touches )
{
if( touches.Count != GetRequiredFingerCount() )
return false;
// check with the delegate (provided we have one set)
if( !CheckCanBeginDelegate( touches ) )
return false;
return true;
}
public virtual bool CheckCanBeginDelegate( FingerGestures.IFingerList touches )
{
if( canBeginDelegate != null && !canBeginDelegate( this, touches ) )
return false;
return true;
}
#region CanBegin Delegate
public delegate bool CanBeginDelegate( GestureRecognizer gr, FingerGestures.IFingerList touches );
CanBeginDelegate canBeginDelegate;
public void SetCanBeginDelegate( CanBeginDelegate f ) { canBeginDelegate = f; }
public CanBeginDelegate GetCanBeginDelegate() { return canBeginDelegate; }
#endregion
#region Abstract methods to implement in derived classes
/// <summary>
/// Return the exact number of active touches required for the gesture to be valid
/// </summary>
protected abstract int GetRequiredFingerCount();
/// <summary>
/// Method called when the gesture recognizer has just started recognizing a valid gesture
/// </summary>
/// <param name="touches">The active touches</param>
protected abstract void OnBegin( FingerGestures.IFingerList touches );
/// <summary>
/// Method called on each frame that the gesture recognizer is in an active state
/// </summary>
/// <param name="touches">The active touches</param>
/// <returns>The new state the gesture recognizer should be in</returns>
protected abstract GestureState OnActive( FingerGestures.IFingerList touches );
#endregion
#region Touch Filter
FingerGestures.ITouchFilter touchFilter = null;
/// <summary>
/// Get or set the touch filter used to modify the list of active touches about to be processed by the gesture recognizer
/// </summary>
public FingerGestures.ITouchFilter TouchFilter
{
get { return touchFilter; }
set { touchFilter = value; }
}
#endregion
#region Utils
/// <summary>
/// Check if all the touches in the list started recently
/// </summary>
/// <param name="touches">The touches to evaluate</param>
/// <returns>True if the age of each touch in the list is under a set threshold</returns>
protected bool Young( FingerGestures.IFingerList touches )
{
FingerGestures.Finger oldestTouch = touches.GetOldest();
if( oldestTouch == null )
return false;
float elapsedTimeSinceFirstTouch = Time.time - oldestTouch.StarTime;
return elapsedTimeSinceFirstTouch < 0.25f;
}
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/Base/GestureRecognizer.cs
|
C#
|
asf20
| 9,060
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Base class for multi-finger gestures that require individual access to each finger position (as opposed to averaged position)
/// </summary>
public abstract class MultiFingerGestureRecognizer : GestureRecognizer
{
Vector2[] startPos;
protected Vector2[] StartPosition
{
get { return startPos; }
set { startPos = value; }
}
Vector2[] pos;
protected Vector2[] Position
{
get { return pos; }
set { pos = value; }
}
protected override void Start()
{
base.Start();
OnFingerCountChanged( GetRequiredFingerCount() );
}
protected void OnFingerCountChanged( int fingerCount )
{
StartPosition = new Vector2[fingerCount];
Position = new Vector2[fingerCount];
}
public int RequiredFingerCount
{
get { return GetRequiredFingerCount(); }
}
/// <summary>
/// Get the position of the finger at the given index
/// </summary>
/// <param name="index">index of the finger to retrieve</param>
public Vector2 GetPosition( int index )
{
return pos[index];
}
/// <summary>
/// Get the initial position of the finger at the given index
/// </summary>
/// <param name="index">index of the finger to retrieve</param>
public Vector2 GetStartPosition( int index )
{
return startPos[index];
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/Base/MultiFingerGestureRecognizer.cs
|
C#
|
asf20
| 1,505
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Base class used by most common gestures that can be performed with
/// and arbitrary number of fingers, such as drag, tap, swipe...
///
/// The position of the fingers are averaged and stored in the
/// StartPosition and/or Position fields
/// </summary>
public abstract class AveragedGestureRecognizer : GestureRecognizer
{
/// <summary>
/// Exact number of touches required for the gesture to be recognized
/// </summary>
public int RequiredFingerCount = 1;
Vector2 startPos = Vector2.zero;
Vector2 pos = Vector2.zero;
protected override int GetRequiredFingerCount()
{
return RequiredFingerCount;
}
/// <summary>
/// Initial finger(s) position
/// </summary>
public Vector2 StartPosition
{
get { return startPos; }
protected set { startPos = value; }
}
/// <summary>
/// Current finger(s) position
/// </summary>
public Vector2 Position
{
get { return pos; }
protected set { pos = value; }
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/Components/Base/AveragedGestureRecognizer.cs
|
C#
|
asf20
| 1,131
|
using UnityEngine;
using System.Collections;
public class FingerGesturesPrefabs : MonoBehaviour
{
public FingerMotionDetector fingerMotion;
public DragGestureRecognizer fingerDrag;
public TapGestureRecognizer fingerTap;
public SwipeGestureRecognizer fingerSwipe;
public LongPressGestureRecognizer fingerLongPress;
public DragGestureRecognizer drag;
public TapGestureRecognizer tap;
public SwipeGestureRecognizer swipe;
public LongPressGestureRecognizer longPress;
public PinchGestureRecognizer pinch;
public RotationGestureRecognizer rotation;
public DragGestureRecognizer twoFingerDrag;
public TapGestureRecognizer twoFingerTap;
public SwipeGestureRecognizer twoFingerSwipe;
public LongPressGestureRecognizer twoFingerLongPress;
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/FingerGesturesPrefabs.cs
|
C#
|
asf20
| 818
|
using UnityEngine;
using System.Collections;
/// <summary>
/// This tracks input gestures for a touch-screen device (mobiles)
/// </summary>
public class TouchScreenGestures : FingerGestures
{
/// <summary>
/// Maximum number of simultaneous fingers to track
/// </summary>
public int maxFingers = 5;
public override int MaxFingers
{
get { return maxFingers; }
}
protected override void Start()
{
finger2touchMap = new int[MaxFingers];
base.Start();
}
#region FingerGestures Implementation
protected override FingerGestures.FingerPhase GetPhase( Finger finger )
{
if( HasValidTouch( finger ) )
{
UnityEngine.Touch touch = GetTouch( finger );
switch( touch.phase )
{
case UnityEngine.TouchPhase.Began:
return FingerPhase.Began;
case UnityEngine.TouchPhase.Moved:
return FingerPhase.Moved;
case UnityEngine.TouchPhase.Stationary:
return FingerPhase.Stationary;
default:
return FingerPhase.Ended;
}
}
return FingerPhase.None;
}
protected override Vector2 GetPosition( Finger finger )
{
UnityEngine.Touch touch = GetTouch( finger );
return touch.position;
}
#endregion
#region Touch > Finger mapping
UnityEngine.Touch nullTouch = new UnityEngine.Touch();
int[] finger2touchMap; // finger.index -> touch index map
void UpdateFingerTouchMap()
{
for( int i = 0; i < finger2touchMap.Length; ++i )
finger2touchMap[i] = -1;
for( int i = 0; i < Input.touchCount; ++i )
{
int fingerIndex = Input.touches[i].fingerId;
if( fingerIndex < finger2touchMap.Length )
finger2touchMap[fingerIndex] = i;
}
}
bool HasValidTouch( Finger finger )
{
return finger2touchMap[finger.Index] != -1;
}
UnityEngine.Touch GetTouch( Finger finger )
{
int touchIndex = finger2touchMap[finger.Index];
if( touchIndex == -1 )
return nullTouch;
return Input.touches[touchIndex];
}
#endregion
protected override void Update()
{
UpdateFingerTouchMap();
base.Update();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/TouchScreenGestures.cs
|
C#
|
asf20
| 2,503
|
using UnityEngine;
using System.Collections;
/// <summary>
/// This class is used to create and initialise the proper FigureGesture implementation based on the current platform the application is being run on
/// </summary>
public class FingerGesturesInitializer : MonoBehaviour
{
public FingerGestures editorGestures;
public FingerGestures desktopGestures;
public FingerGestures iosGestures;
public FingerGestures androidGestures;
// whether to make the FingerGesture persist through scene loads
public bool makePersistent = true;
void Awake()
{
if( !FingerGestures.Instance )
{
FingerGestures prefab;
if( Application.isEditor )
{
prefab = editorGestures;
}
else
{
#if UNITY_IPHONE
prefab = iosGestures;
#elif UNITY_ANDROID
prefab = androidGestures;
#else
prefab = desktopGestures;
#endif
}
Debug.Log( "Creating FingerGestures using " + prefab.name );
FingerGestures instance = Instantiate( prefab ) as FingerGestures;
instance.name = prefab.name;
if( makePersistent )
DontDestroyOnLoad( instance.gameObject );
}
Destroy( this.gameObject );
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/FingerGesturesInitializer.cs
|
C#
|
asf20
| 1,176
|
// FingerGestures v2.2 (November 15th 2011)
// The FingerGestures library is copyright (c) of William Ravaine
// Please send feedback or bug reports to spk@fatalfrog.com
// More FingerGestures information at http://www.fatalfrog.com/?page_id=140
// Visit my website @ http://www.fatalfrog.com
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// The main interface to the FingerGestures library.
/// Most of the methods are static because FingerGestures is meant to be a singleton.
/// </summary>
public abstract class FingerGestures : MonoBehaviour
{
// If you are not familiar with events and delegates, or need a refresher, please refer to this youtube video made by the guys
// at Prime31 Studios - http://www.youtube.com/watch?v=N2zdwKIsXJs
#region Global Events (Quick Use Mode)
// The following events are wrapper/proxies for the default gesture recognizers that are automatically installed and configured at start, provided the relevant options are enabled.
// Only the most relevant data for each event are passed as arguments to the event delegate. This allows developers to quickly use FingerGestures with minimal knowledge of the inner
// workings of the library.
// The default gesture recognizers can be accessed via the FingerGestures.Defaults interface.
#region Per-Finger events
//NOTE: events in this category fire independently for each finger, regardless of the state of other fingers
// You can use FingerGestures.GetFinger(fingerIndex) to retrieve the Finger object corresponding to the fingerIndex event parameter
#region Delegates
/// <summary>
/// Delegate for the OnFingerDown event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
public delegate void FingerDownEventHandler( int fingerIndex, Vector2 fingerPos );
/// <summary>
/// Delegate for the OnFingerUp event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
/// <param name="timeHeldDown">How long the finger has been held down before getting released, in seconds</param>
public delegate void FingerUpEventHandler( int fingerIndex, Vector2 fingerPos, float timeHeldDown );
/// <summary>
/// Delegate for the OnFingerStationaryBegin event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
public delegate void FingerStationaryBeginEventHandler( int fingerIndex, Vector2 fingerPos );
/// <summary>
/// Delegate for the OnFingerStationary event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
/// <param name="elapsedTime">How much time has elapsed, in seconds, since the last OnFingerStationaryBegin fired on this finger</param>
public delegate void FingerStationaryEventHandler( int fingerIndex, Vector2 fingerPos, float elapsedTime );
/// <summary>
/// Delegate for the OnFingerStationaryEnd event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
/// <param name="elapsedTime">How much time has elapsed, in seconds, since the last OnFingerStationaryBegin fired on this finger</param>
public delegate void FingerStationaryEndEventHandler( int fingerIndex, Vector2 fingerPos, float elapsedTime );
/// <summary>
/// Delegate for the OnFingerMoveBegin, OnFingerMove, OnFingerMoveEnd events
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
public delegate void FingerMoveEventHandler( int fingerIndex, Vector2 fingerPos );
/// <summary>
/// Delegate for the OnFingernLongPress event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
public delegate void FingerLongPressEventHandler( int fingerIndex, Vector2 fingerPos );
/// <summary>
/// Delegate for the OnFingernTap event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
/// <param name="tapCount">How many times the user has consecutively tapped his finger at this location</param>
public delegate void FingerTapEventHandler( int fingerIndex, Vector2 fingerPos, int tapCount );
/// <summary>
/// Delegate for the OnFingernSwipe event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="startPos">Initial position of the finger</param>
/// <param name="direction">Direction of the swipe gesture</param>
/// <param name="velocity">How quickly the finger has moved (in screen pixels per second)</param>
public delegate void FingerSwipeEventHandler( int fingerIndex, Vector2 startPos, SwipeDirection direction, float velocity );
/// <summary>
/// Delegate for the OnFingernDragBegin event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
/// <param name="startPos">The initial finger position on the screen.</param>
/// <remark>Since the finger has to move beyond a certain treshold distance (specified by the moveThreshold property)
/// before the gesture registers as a drag motion, fingerPos and startPos are likely to be different if you specified a non-zero moveThreshold.</remark>
public delegate void FingerDragBeginEventHandler( int fingerIndex, Vector2 fingerPos, Vector2 startPos );
/// <summary>
/// Delegate for the OnFingernDragMove event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
/// <param name="delta">How much the finger has moved since the last update. This is the difference between the previous finger position and the new one.</param>
public delegate void FingerDragMoveEventHandler( int fingerIndex, Vector2 fingerPos, Vector2 delta );
/// <summary>
/// Delegate for the OnFingernDragEnd event
/// </summary>
/// <param name="fingerIndex">0-based index uniquely indentifying a specific finger</param>
/// <param name="fingerPos">Current position of the finger on the screen</param>
public delegate void FingerDragEndEventHandler( int fingerIndex, Vector2 fingerPos );
#endregion
#region Events
/// <summary>
/// Event fired when a finger's OnDown event fires
/// <seealso cref="Finger.OnDown"/>
/// </summary>
public static event FingerDownEventHandler OnFingerDown;
/// <summary>
/// Event fired when a finger's OnUp event fires
/// <seealso cref="Finger.OnUp"/>
/// </summary>
public static event FingerUpEventHandler OnFingerUp;
/// <summary>
/// Event fired when a finger's default motion detector OnStationaryBegin event fires
/// <seealso cref="FingerMotionDetector.OnStationaryBegin"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Motion"/>
/// </summary>
public static event FingerStationaryBeginEventHandler OnFingerStationaryBegin;
/// <summary>
/// Event fired when a finger's default motion detector OnStationary event fires
/// <seealso cref="FingerMotionDetector.OnStationary"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Motion"/>
/// </summary>
public static event FingerStationaryEventHandler OnFingerStationary;
/// <summary>
/// Event fired when a finger's default motion detector OnStationaryEnd event fires
/// <seealso cref="FingerMotionDetector.OnStationaryEnd"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Motion"/>
/// </summary>
public static event FingerStationaryEndEventHandler OnFingerStationaryEnd;
/// <summary>
/// Event fired when a finger's default motion detector OnMoveBegin event fires
/// <seealso cref="FingerMotionDetector.OnMoveBegin"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Motion"/>
/// </summary>
public static event FingerMoveEventHandler OnFingerMoveBegin;
/// <summary>
/// Event fired when a finger's default motion detector OnMove event fires
/// <seealso cref="FingerMotionDetector.OnMove"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Motion"/>
/// </summary>
public static event FingerMoveEventHandler OnFingerMove;
/// <summary>
/// Event fired when a finger's default motion detector OnMoveEnd event fires
/// <seealso cref="FingerMotionDetector.OnMoveEnd"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Motion"/>
/// </summary>
public static event FingerMoveEventHandler OnFingerMoveEnd;
/// <summary>
/// Event fired when a finger's long-press gesture recognizer OnLongPress event fires
/// </summary>
/// <seealso cref="LongPressGestureRecognizer.OnLongPress"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.LongPress"/>
public static event FingerLongPressEventHandler OnFingerLongPress;
/// <summary>
/// Event fired when a finger's drag gesture recognizer OnDragBegin event fires
/// <seealso cref="DragGestureRecognizer.OnDragBegin"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Drag"/>
/// </summary>
public static event FingerDragBeginEventHandler OnFingerDragBegin;
/// <summary>
/// Event fired when a finger's drag gesture recognizer OnDragMove event fires
/// <seealso cref="DragGestureRecognizer.OnDragMove"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Drag"/>
/// </summary>
public static event FingerDragMoveEventHandler OnFingerDragMove;
/// <summary>
/// Event fired when a finger's drag gesture recognizer OnDragEnd event fires
/// <see cref="DragGestureRecognizer.OnDragEnd"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Drag"/>
/// </summary>
public static event FingerDragEndEventHandler OnFingerDragEnd;
/// <summary>
/// Event fired when a finger's tap gesture recognizer OnTap event fires
/// </summary>
/// <seealso cref="TapGestureRecognizer.OnTap"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Tap"/>
public static event FingerTapEventHandler OnFingerTap;
/// <summary>
/// Event fired when a finger's swipe gesture recognizer OnSwipe event fires
/// </summary>
/// <seealso cref="SwipeGestureRecognizer.OnSwipe"/>
/// <seealso cref="FingerGestures.Defaults.Fingers.Swipe"/>
public static event FingerSwipeEventHandler OnFingerSwipe;
#endregion
#region Event-Raising Wrappers
internal static void RaiseOnFingerDown( int fingerIndex, Vector2 fingerPos )
{
if( OnFingerDown != null )
OnFingerDown( fingerIndex, fingerPos );
}
internal static void RaiseOnFingerUp( int fingerIndex, Vector2 fingerPos, float timeHeldDown )
{
if( OnFingerUp != null )
OnFingerUp( fingerIndex, fingerPos, timeHeldDown );
}
internal static void RaiseOnFingerStationaryBegin( int fingerIndex, Vector2 fingerPos )
{
if( OnFingerStationaryBegin != null )
OnFingerStationaryBegin( fingerIndex, fingerPos );
}
internal static void RaiseOnFingerStationary( int fingerIndex, Vector2 fingerPos, float elapsedTime )
{
if( OnFingerStationary != null )
OnFingerStationary( fingerIndex, fingerPos, elapsedTime );
}
internal static void RaiseOnFingerStationaryEnd( int fingerIndex, Vector2 fingerPos, float elapsedTime )
{
if( OnFingerStationaryEnd != null )
OnFingerStationaryEnd( fingerIndex, fingerPos, elapsedTime );
}
internal static void RaiseOnFingerMoveBegin( int fingerIndex, Vector2 fingerPos )
{
if( OnFingerMoveBegin != null )
OnFingerMoveBegin( fingerIndex, fingerPos );
}
internal static void RaiseOnFingerMove( int fingerIndex, Vector2 fingerPos )
{
if( OnFingerMove != null )
OnFingerMove( fingerIndex, fingerPos );
}
internal static void RaiseOnFingerMoveEnd( int fingerIndex, Vector2 fingerPos )
{
if( OnFingerMoveEnd != null )
OnFingerMoveEnd( fingerIndex, fingerPos );
}
internal static void RaiseOnFingerLongPress( int fingerIndex, Vector2 fingerPos )
{
if( OnFingerLongPress != null )
OnFingerLongPress( fingerIndex, fingerPos );
}
internal static void RaiseOnFingerDragBegin( int fingerIndex, Vector2 fingerPos, Vector2 startPos )
{
if( OnFingerDragBegin != null )
OnFingerDragBegin( fingerIndex, fingerPos, startPos );
}
internal static void RaiseOnFingerDragMove( int fingerIndex, Vector2 fingerPos, Vector2 delta )
{
if( OnFingerDragMove != null )
OnFingerDragMove( fingerIndex, fingerPos, delta );
}
internal static void RaiseOnFingerDragEnd( int fingerIndex, Vector2 fingerPos )
{
if( OnFingerDragEnd != null )
OnFingerDragEnd( fingerIndex, fingerPos );
}
internal static void RaiseOnFingerTap( int fingerIndex, Vector2 fingerPos, int tapCount )
{
if( OnFingerTap != null )
OnFingerTap( fingerIndex, fingerPos, tapCount );
}
internal static void RaiseOnFingerSwipe( int fingerIndex, Vector2 startPos, SwipeDirection direction, float velocity )
{
if( OnFingerSwipe != null )
OnFingerSwipe( fingerIndex, startPos, direction, velocity );
}
#endregion
#endregion
#region Global Gesture Events
//NOTE: events in this category are not global, in the sense that they take into account the current state of all the fingers. For instance,
// a single-finger gesture event such as OnTap will only fire if there is exactly one finger touching the screen (and tapping). If there are more touches,
// the gesture recognizer will fail, and the event will not be risen.
#region Delegates
/// <summary>
/// Delegate for the OnLongPress event
/// </summary>
/// <param name="fingerPos">Screen position where the press occured</param>
public delegate void LongPressEventHandler( Vector2 fingerPos );
/// <summary>
/// Delegate for the OnTap event
/// </summary>
/// <param name="fingerPos">Screen position where the tap occured</param>
/// <param name="tapCount">Number of conseuctive taps the user has performed at this location</param>
public delegate void TapEventHandler( Vector2 fingerPos, int tapCount );
/// <summary>
/// Delegate for the OnSwipe event
/// </summary>
/// <param name="startPos">Initial finger position when the swipe gesture started</param>
/// <param name="direction">Direction of the swipe gesture</param>
/// <param name="velocity">How quickly the finger has moved (in screen pixels per second)</param>
public delegate void SwipeEventHandler( Vector2 startPos, FingerGestures.SwipeDirection direction, float velocity );
/// <summary>
/// Delegate for the OnDragBegin event
/// </summary>
/// <param name="fingerPos">The current finger position on the screen</param>
/// <param name="startPos">The initial screen position the gesture started from</param>
/// <remark>These two values can differ if the drag gesture recognizer's MoveThreshold is non-zero</remark>
public delegate void DragBeginEventHandler( Vector2 fingerPos, Vector2 startPos );
/// <summary>
/// Delegate for the OnDragMove event
/// </summary>
/// <param name="fingerPos">Current finger position on the screen</param>
/// <param name="delta">How much the finger has moved since the last update. This is the difference between the previous finger position and the new one.</param>
public delegate void DragMoveEventHandler( Vector2 fingerPos, Vector2 delta );
/// <summary>
/// Delegate for the OnDragEnd event
/// </summary>
/// <param name="fingerPos">Current position of the finger on the screen</param>
public delegate void DragEndEventHandler( Vector2 fingerPos );
/// <summary>
/// Delegate for the OnPinchBegin and OnPinchEnd events
/// </summary>
/// <param name="fingerPos1">First finger screen position</param>
/// <param name="fingerPos2">Second finger screen position</param>
public delegate void PinchEventHandler( Vector2 fingerPos1, Vector2 fingerPos2 );
/// <summary>
/// Delegate for the OnPinchMove event
/// </summary>
/// <param name="fingerPos1">First finger screen position</param>
/// <param name="fingerPos2">Second finger screen position</param>
/// <param name="delta">How much the distance between the two fingers has changed since the last update. A negative value means the two fingers got closer, while a positive value means they moved further apart</param>
public delegate void PinchMoveEventHandler( Vector2 fingerPos1, Vector2 fingerPos2, float delta );
/// <summary>
/// Delegate for the OnRotationBegin event
/// </summary>
/// <param name="fingerPos1">First finger screen position</param>
/// <param name="fingerPos2">Second finger screen position</param>
public delegate void RotationBeginEventHandler( Vector2 fingerPos1, Vector2 fingerPos2 );
/// <summary>
/// Delegate for the OnRotationMove event
/// </summary>
/// <param name="fingerPos1">First finger screen position</param>
/// <param name="fingerPos2">Second finger screen position</param>
/// <param name="rotationAngleDelta">Angle difference, in degrees, since the last update.</param>
public delegate void RotationMoveEventHandler( Vector2 fingerPos1, Vector2 fingerPos2, float rotationAngleDelta );
/// <summary>
/// Delegate for the OnRotationEnd event
/// </summary>
/// <param name="fingerPos1">First finger screen position</param>
/// <param name="fingerPos2">Second finger screen position</param>
/// <param name="totalRotationAngle">Total rotation performed during the gesture, in degrees</param>
public delegate void RotationEndEventHandler( Vector2 fingerPos1, Vector2 fingerPos2, float totalRotationAngle );
#endregion
#region Events
/// <summary>
/// Event fired when the default long-press gesture recognizer OnLongPress event fires
/// </summary>
/// <seealso cref="LongPressGestureRecognizer.OnLongPress"/>
/// <seealso cref="FingerGestures.Defaults.LongPress"/>
public static event LongPressEventHandler OnLongPress;
/// <summary>
/// Event fired when the default drag gesture recognizer's OnDragBegin event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnDragBegin"/>
/// <seealso cref="FingerGestures.Defaults.Drag"/>
public static event DragBeginEventHandler OnDragBegin;
/// <summary>
/// Event fired when the default drag gesture recognizer's OnDragMove event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnDragMove"/>
/// <seealso cref="FingerGestures.Defaults.Drag"/>
public static event DragMoveEventHandler OnDragMove;
/// <summary>
/// Event fired when the default drag gesture recognizer's OnDragEnd event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnDragEnd"/>
/// <seealso cref="FingerGestures.Defaults.Drag"/>
public static event DragEndEventHandler OnDragEnd;
/// <summary>
/// Event fired when the default tap gesture recognizer's OnTap event fires
/// </summary>
/// <seealso cref="TapGestureRecognizer.OnTap"/>
/// <seealso cref="FingerGestures.Defaults.Tap"/>
public static event TapEventHandler OnTap;
/// <summary>
/// Event fired when the default swipe gesture recognizer's OnSwipe event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnDragEnd"/>
/// <seealso cref="FingerGestures.Defaults.Drag"/>
public static event SwipeEventHandler OnSwipe;
/// <summary>
/// Event fired when the default pinch gesture recognizer's OnPinchBegin event fires
/// </summary>
/// <seealso cref="PinchGestureRecognizer.OnPinchBegin"/>
/// <seealso cref="FingerGestures.Defaults.Pinch"/>
public static event PinchEventHandler OnPinchBegin;
/// <summary>
/// Event fired when the default pinch gesture recognizer's OnPinchMove event fires
/// </summary>
/// <seealso cref="PinchGestureRecognizer.OnPinchMove"/>
/// <seealso cref="FingerGestures.Defaults.Pinch"/>
public static event PinchMoveEventHandler OnPinchMove;
/// <summary>
/// Event fired when the default pinch gesture recognizer's OnPinchEnd event fires
/// <seealso cref="PinchGestureRecognizer.OnPinchEnd"/>
/// <seealso cref="FingerGestures.Defaults.Pinch"/>
/// </summary>
public static event PinchEventHandler OnPinchEnd;
/// <summary>
/// Event fired when the default pinch gesture recognizer's OnRotationBegin event fires
/// <seealso cref="RotationGestureRecognizer.OnRotationBegin"/>
/// <seealso cref="FingerGestures.Defaults.Rotation"/>
/// </summary>
public static event RotationBeginEventHandler OnRotationBegin;
/// <summary>
/// Event fired when the default pinch gesture recognizer's OnRotationMove event fires
/// <seealso cref="RotationGestureRecognizer.OnRotationMove"/>
/// <seealso cref="FingerGestures.Defaults.Rotation"/>
/// </summary>
public static event RotationMoveEventHandler OnRotationMove;
/// <summary>
/// Event fired when the default pinch gesture recognizer's OnRotationEnd event fires
/// <seealso cref="RotationGestureRecognizer.OnRotationEnd"/>
/// <seealso cref="FingerGestures.Defaults.Rotation"/>
/// </summary>
public static event RotationEndEventHandler OnRotationEnd;
#region Two-Finger Versions
/// <summary>
/// Event fired when the default two-finger drag gesture recognizer's OnDragBegin event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnDragBegin"/>
/// <seealso cref="FingerGestures.Defaults.TwoFingerDrag"/>
public static event DragBeginEventHandler OnTwoFingerDragBegin;
/// <summary>
/// Event fired when the default two-finger drag gesture recognizer's OnDragMove event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnDragMove"/>
/// <seealso cref="FingerGestures.Defaults.TwoFingerDrag"/>
public static event DragMoveEventHandler OnTwoFingerDragMove;
/// <summary>
/// Event fired when the default two-finger drag gesture recognizer's OnDragEnd event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnDragEnd"/>
/// <seealso cref="FingerGestures.Defaults.TwoFingerDrag"/>
public static event DragEndEventHandler OnTwoFingerDragEnd;
/// <summary>
/// Event fired when the default two-finger tap gesture recognizer's OnTap event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnTap"/>
/// <seealso cref="FingerGestures.Defaults.TwoFingerTap"/>
public static event TapEventHandler OnTwoFingerTap;
/// <summary>
/// Event fired when the default two-finger tap gesture recognizer's OnSwipe event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnSwipe"/>
/// <seealso cref="FingerGestures.Defaults.TwoFingerSwipe"/>
public static event SwipeEventHandler OnTwoFingerSwipe;
/// <summary>
/// Event fired when the default two-finger long-press gesture recognizer's OnLongPress event fires
/// </summary>
/// <seealso cref="DragGestureRecognizer.OnLongPress"/>
/// <seealso cref="FingerGestures.Defaults.TwoFingerLongPress"/>
public static event LongPressEventHandler OnTwoFingerLongPress;
#endregion
#endregion
#region Event-Raising Wrappers
internal static void RaiseOnLongPress( Vector2 fingerPos )
{
if( OnLongPress != null )
OnLongPress( fingerPos );
}
internal static void RaiseOnDragBegin( Vector2 fingerPos, Vector2 startPos )
{
if( OnDragBegin != null )
OnDragBegin( fingerPos, startPos );
}
internal static void RaiseOnDragMove( Vector2 fingerPos, Vector2 delta )
{
if( OnDragMove != null )
OnDragMove( fingerPos, delta );
}
internal static void RaiseOnDragEnd( Vector2 fingerPos )
{
if( OnDragEnd != null )
OnDragEnd( fingerPos );
}
internal static void RaiseOnTap( Vector2 fingerPos, int tapCount )
{
if( OnTap != null )
OnTap( fingerPos, tapCount );
}
internal static void RaiseOnSwipe( Vector2 startPos, SwipeDirection direction, float velocity )
{
if( OnSwipe != null )
OnSwipe( startPos, direction, velocity );
}
internal static void RaiseOnPinchBegin( Vector2 fingerPos1, Vector2 fingerPos2 )
{
if( OnPinchBegin != null )
OnPinchBegin( fingerPos1, fingerPos2 );
}
internal static void RaiseOnPinchMove( Vector2 fingerPos1, Vector2 fingerPos2, float delta )
{
if( OnPinchMove != null )
OnPinchMove( fingerPos1, fingerPos2, delta );
}
internal static void RaiseOnPinchEnd( Vector2 fingerPos1, Vector2 fingerPos2 )
{
if( OnPinchEnd != null )
OnPinchEnd( fingerPos1, fingerPos2 );
}
internal static void RaiseOnRotationBegin( Vector2 fingerPos1, Vector2 fingerPos2 )
{
if( OnRotationBegin != null )
OnRotationBegin( fingerPos1, fingerPos2 );
}
internal static void RaiseOnRotationMove( Vector2 fingerPos1, Vector2 fingerPos2, float rotationAngleDelta )
{
if( OnRotationMove != null )
OnRotationMove( fingerPos1, fingerPos2, rotationAngleDelta );
}
internal static void RaiseOnRotationEnd( Vector2 fingerPos1, Vector2 fingerPos2, float totalRotationAngle )
{
if( OnRotationEnd != null )
OnRotationEnd( fingerPos1, fingerPos2, totalRotationAngle );
}
#region Two Finger Versions
internal static void RaiseOnTwoFingerLongPress( Vector2 fingerPos )
{
if( OnTwoFingerLongPress != null )
OnTwoFingerLongPress( fingerPos );
}
internal static void RaiseOnTwoFingerDragBegin( Vector2 fingerPos, Vector2 startPos )
{
if( OnTwoFingerDragBegin != null )
OnTwoFingerDragBegin( fingerPos, startPos );
}
internal static void RaiseOnTwoFingerDragMove( Vector2 fingerPos, Vector2 delta )
{
if( OnTwoFingerDragMove != null )
OnTwoFingerDragMove( fingerPos, delta );
}
internal static void RaiseOnTwoFingerDragEnd( Vector2 fingerPos )
{
if( OnTwoFingerDragEnd != null )
OnTwoFingerDragEnd( fingerPos );
}
internal static void RaiseOnTwoFingerTap( Vector2 fingerPos, int tapCount )
{
if( OnTwoFingerTap != null )
OnTwoFingerTap( fingerPos, tapCount );
}
internal static void RaiseOnTwoFingerSwipe( Vector2 startPos, SwipeDirection direction, float velocity )
{
if( OnTwoFingerSwipe != null )
OnTwoFingerSwipe( startPos, direction, velocity );
}
#endregion
#endregion
#endregion
#endregion
/// <summary>
/// Access to the FingerGestures singleton instance
/// </summary>
public static FingerGestures Instance
{
get { return FingerGestures.instance; }
}
#region Finger
/// <summary>
/// Finger Phase
/// </summary>
public enum FingerPhase
{
None,
/// <summary>
/// The finger just touched the screen
/// </summary>
Began,
/// <summary>
/// The finger just moved
/// </summary>
Moved,
/// <summary>
/// The finger is stationary
/// </summary>
Stationary,
/// <summary>
/// The finger was lifted off the screen
/// </summary>
Ended,
}
/// <summary>
/// Finger
///
/// This provides an abstraction for a finger that can touch and move around the screen.
/// As opposed to Unity's Touch object, a Finger exists independently of whether it is
/// currently touching the screen or not
/// </summary>
public class Finger
{
#region Properties
/// <summary>
/// Unique identifier for this finger.
/// For touch screen gestures, this corresponds to Touch.index, and the button index for mouse gestures.
/// </summary>
public int Index
{
get { return index; }
}
/// <summary>
/// Current phase
/// </summary>
public FingerPhase Phase
{
get { return phase; }
}
/// <summary>
/// Return true if the finger is currently down
/// </summary>
public bool IsDown
{
get { return down; }
}
/// <summary>
/// Return true if the finger was down during the previous update/frame
/// </summary>
public bool WasDown
{
get { return wasDown; }
}
/// <summary>
/// Get the time of first screen contact
/// </summary>
public float StarTime
{
get { return startTime; }
}
/// <summary>
/// Get the position of first screen contact
/// </summary>
public Vector2 StartPosition
{
get { return startPos; }
}
/// <summary>
/// Get the current position
/// </summary>
public Vector2 Position
{
get { return pos; }
}
/// <summary>
/// Get the position during the previous frame
/// </summary>
public Vector2 PreviousPosition
{
get { return prevPos; }
}
/// <summary>
/// Get the difference between previous and current position
/// </summary>
public Vector2 DeltaPosition
{
get { return deltaPos; }
}
/// <summary>
/// Get the distance traveled from initial position
/// </summary>
public float DistanceFromStart
{
get { return distFromStart; }
}
#endregion
#region Events
/// <summary>
/// Delegate for OnDown & OnUp
/// </summary>
/// <param name="finger">the finger firing the event</param>
public delegate void FingerEventDelegate( Finger finger );
/// <summary>
/// Event fired on the first frame the finger is down
/// </summary>
public event FingerEventDelegate OnDown;
/// <summary>
/// Event fired when the finger, previously down, has just been released. e.g. this would be the equivalent of a "mouse up" button event.
/// </summary>
public event FingerEventDelegate OnUp;
#endregion
#region Internal
int index = 0;
bool wasDown = false;
bool down = false;
float startTime = 0;
FingerPhase phase = FingerPhase.None;
Vector2 startPos = Vector2.zero;
Vector2 pos = Vector2.zero;
Vector2 prevPos = Vector2.zero;
Vector2 deltaPos = Vector2.zero;
float distFromStart = 0;
public Finger( int index )
{
this.index = index;
}
public override string ToString()
{
return "Finger" + index;
}
internal void Update( FingerPhase newPhase, Vector2 newPos )
{
// validate phase transitions
if( phase != newPhase )
{
// In low framerate situations, it is possible to miss some input updates and thus
// skip the "Ended" phase
if( newPhase == FingerPhase.None && phase != FingerPhase.Ended )
{
Debug.LogWarning( "Correcting bad FingerPhase transition (FingerPhase.Ended skipped)" );
Update( FingerPhase.Ended, PreviousPosition );
return;
}
// cannot get a Moved or Stationary phase without being down first
if( !down && ( newPhase == FingerPhase.Moved || newPhase == FingerPhase.Stationary ) )
{
Debug.LogWarning( "Correcting bad FingerPhase transition (FingerPhase.Began skipped)" );
Update( FingerPhase.Began, newPos );
return;
}
if( ( down && newPhase == FingerPhase.Began ) || ( !down && newPhase == FingerPhase.Ended ) )
{
Debug.LogWarning( "Invalid state FingerPhase transition from " + phase + " to " + newPhase + " - Skipping." );
return;
}
}
else // same phase as before
{
if( newPhase == FingerPhase.Began || newPhase == FingerPhase.Ended )
{
Debug.LogWarning( "Duplicated FingerPhase." + newPhase.ToString() + " - skipping." );
return;
}
}
if( newPhase != FingerPhase.None )
{
if( newPhase == FingerPhase.Ended )
{
// release
down = false;
}
else
{
if( newPhase == FingerPhase.Began )
{
// activate
down = true;
startPos = newPos;
prevPos = newPos;
startTime = Time.time;
}
prevPos = pos;
pos = newPos;
deltaPos = pos - prevPos;
distFromStart = Vector3.Distance( startPos, pos );
}
}
phase = newPhase;
}
/// <summary>
/// PostUpdate
/// We use PostUpdate() to raise the OnDown/OnUp events after all the fingers have been properly updated
/// </summary>
internal void PostUpdate()
{
if( wasDown != down )
{
if( down )
{
if( OnDown != null )
OnDown( this );
}
else
{
if( OnUp != null )
OnUp( this );
}
}
wasDown = down;
}
#endregion
}
/// <summary>
/// Get a finger by its index
/// </summary>
public static Finger GetFinger( int index )
{
return instance.fingers[index];
}
/// <summary>
/// List of fingers currently touching the screen
/// </summary>
public static IFingerList Touches
{
get { return instance.touches; }
}
#endregion
#region Engine Callbacks
protected virtual void OnEnable()
{
instance = this;
InitFingers( MaxFingers );
}
protected virtual void Start()
{
// reinit
if( fingers == null )
InitFingers( MaxFingers );
}
public delegate void FingersUpdatedEventDelegate();
public static event FingersUpdatedEventDelegate OnFingersUpdated;
protected virtual void Update()
{
UpdateFingers();
if( OnFingersUpdated != null )
OnFingersUpdated();
}
#endregion
#region Overridable methods
/// <summary>
/// Maximum number of simultaneous fingers supported
/// </summary>
public abstract int MaxFingers { get; }
/// <summary>
/// Return the new phase of the finger for this frame
/// </summary>
protected abstract FingerPhase GetPhase( Finger finger );
/// <summary>
/// Return the new position of the finger on the screen for this frame
/// </summary>
protected abstract Vector2 GetPosition( Finger finger );
#endregion
#region Internal
// access to the singleton
static FingerGestures instance;
#region Fingers Management
Finger[] fingers;
FingerList touches = new FingerList();
void InitFingers( int count )
{
// pre-allocate a touch data entry for each finger
if( fingers == null )
{
fingers = new Finger[count];
for( int i = 0; i < count; ++i )
fingers[i] = new Finger( i );
}
InitDefaultComponents();
}
void UpdateFingers()
{
touches.Clear();
// update all fingers
foreach( Finger finger in fingers )
{
Vector2 pos = Vector2.zero;
FingerPhase phase = GetPhase( finger );
if( phase != FingerPhase.None )
pos = GetPosition( finger );
finger.Update( phase, pos );
if( finger.IsDown )
touches.Add( finger );
}
// post-update
foreach( Finger finger in fingers )
finger.PostUpdate();
}
#endregion
#region Default Per-Finger & Global Gesture Recognizers
public FingerGesturesPrefabs defaultPrefabs; // prefabs
Transform globalComponentNode;
Transform[] fingerComponentNodes;
T CreateDefaultComponent<T>( T prefab, Transform parent ) where T : FGComponent
{
T comp = Instantiate( prefab ) as T;
comp.gameObject.name = prefab.name;
comp.transform.parent = parent;
return comp;
}
T CreateDefaultGlobalComponent<T>( T prefab ) where T : FGComponent
{
return CreateDefaultComponent<T>( prefab, globalComponentNode );
}
T CreateDefaultFingerComponent<T>( Finger finger, T prefab ) where T : FGComponent
{
return CreateDefaultComponent<T>( prefab, fingerComponentNodes[finger.Index] );
}
[System.Serializable]
public class DefaultComponentCreationFlags
{
[System.Serializable]
public class PerFinger
{
public bool enabled = true;
public bool touch = true; // FingerDown & FingerUp
public bool motion = true; // FingerMove & FingerStationary
public bool longPress = true;
public bool drag = true;
public bool swipe = true;
public bool tap = true;
}
[System.Serializable]
public class GlobalGestures
{
public bool enabled = true;
public bool longPress = true;
public bool drag = true;
public bool swipe = true;
public bool tap = true;
public bool pinch = true;
public bool rotation = true;
public bool twoFingerLongPress = true;
public bool twoFingerDrag = true;
public bool twoFingerSwipe = true;
public bool twoFingerTap = true;
}
public PerFinger perFinger;
public GlobalGestures globalGestures;
}
/// <summary>
/// This holds a reference to all the default components/gesture recognizers automatically created at initialization
/// </summary>
public class DefaultComponents
{
public DefaultComponents( int fingerCount )
{
fingers = new FingerComponents[fingerCount];
for( int i = 0; i < fingers.Length; ++i )
fingers[i] = new FingerComponents();
}
/// <summary>
/// Per-Finger components
/// </summary>
public class FingerComponents
{
public FingerMotionDetector Motion;
public LongPressGestureRecognizer LongPress;
public DragGestureRecognizer Drag;
public TapGestureRecognizer Tap;
public SwipeGestureRecognizer Swipe;
}
FingerComponents[] fingers;
public FingerComponents[] Fingers
{
get { return fingers; }
}
// global components
public LongPressGestureRecognizer LongPress;
public DragGestureRecognizer Drag;
public TapGestureRecognizer Tap;
public SwipeGestureRecognizer Swipe;
public PinchGestureRecognizer Pinch;
public RotationGestureRecognizer Rotation;
public LongPressGestureRecognizer TwoFingerLongPress;
public DragGestureRecognizer TwoFingerDrag;
public TapGestureRecognizer TwoFingerTap;
public SwipeGestureRecognizer TwoFingerSwipe;
}
public DefaultComponentCreationFlags defaultCompFlags;
DefaultComponents defaultComponents;
/// <summary>
/// Get access to the default components / gesture recognizers
/// </summary>
public static DefaultComponents Defaults
{
get { return instance.defaultComponents; }
}
Transform CreateNode( string name, Transform parent )
{
GameObject go = new GameObject( name );
go.transform.parent = parent;
return go.transform;
}
void InitDefaultComponents()
{
int fingerCount = fingers.Length;
if( globalComponentNode )
Destroy( globalComponentNode.gameObject );
if( fingerComponentNodes != null )
{
foreach( Transform fingerCompNode in fingerComponentNodes )
Destroy( fingerCompNode.gameObject );
}
globalComponentNode = CreateNode( "Global Components", this.transform );
fingerComponentNodes = new Transform[fingerCount];
for( int i = 0; i < fingerComponentNodes.Length; ++i )
fingerComponentNodes[i] = CreateNode( "Finger" + i, this.transform );
defaultComponents = new DefaultComponents( fingerCount );
if( defaultCompFlags.globalGestures.enabled )
InitGlobalGestures();
if( defaultCompFlags.perFinger.enabled )
{
foreach( Finger finger in fingers )
InitDefaultComponents( finger );
}
}
void InitGlobalGestures()
{
// default long press gesture
if( defaultCompFlags.globalGestures.longPress )
{
LongPressGestureRecognizer longPress = CreateDefaultGlobalComponent( defaultPrefabs.longPress );
longPress.OnLongPress += delegate( LongPressGestureRecognizer rec ) { RaiseOnLongPress( rec.Position ); };
defaultComponents.LongPress = longPress;
}
// default long press gesture
if( defaultCompFlags.globalGestures.twoFingerLongPress )
{
LongPressGestureRecognizer longPress = CreateDefaultGlobalComponent( defaultPrefabs.twoFingerLongPress );
longPress.RequiredFingerCount = 2;
longPress.OnLongPress += delegate( LongPressGestureRecognizer rec ) { RaiseOnTwoFingerLongPress( rec.Position ); };
defaultComponents.TwoFingerLongPress = longPress;
}
// default drag detector
if( defaultCompFlags.globalGestures.drag )
{
DragGestureRecognizer drag = CreateDefaultGlobalComponent( defaultPrefabs.drag );
drag.OnDragBegin += delegate( DragGestureRecognizer rec ) { RaiseOnDragBegin( rec.Position, rec.StartPosition ); };
drag.OnDragMove += delegate( DragGestureRecognizer rec ) { RaiseOnDragMove( rec.Position, rec.MoveDelta ); }; ;
drag.OnDragEnd += delegate( DragGestureRecognizer rec ) { RaiseOnDragEnd( rec.Position ); };
defaultComponents.Drag = drag;
}
// default two-finger drag detector
if( defaultCompFlags.globalGestures.twoFingerDrag )
{
DragGestureRecognizer drag = CreateDefaultGlobalComponent( defaultPrefabs.twoFingerDrag );
drag.RequiredFingerCount = 2;
drag.OnDragBegin += delegate( DragGestureRecognizer rec ) { RaiseOnTwoFingerDragBegin( rec.Position, rec.StartPosition ); };
drag.OnDragMove += delegate( DragGestureRecognizer rec ) { RaiseOnTwoFingerDragMove( rec.Position, rec.MoveDelta ); }; ;
drag.OnDragEnd += delegate( DragGestureRecognizer rec ) { RaiseOnTwoFingerDragEnd( rec.Position ); };
defaultComponents.TwoFingerDrag = drag;
}
// default swipe detector
if( defaultCompFlags.globalGestures.swipe )
{
SwipeGestureRecognizer swipe = CreateDefaultGlobalComponent( defaultPrefabs.swipe );
swipe.OnSwipe += delegate( SwipeGestureRecognizer rec ) { RaiseOnSwipe( rec.StartPosition, rec.Direction, rec.Velocity ); };
defaultComponents.Swipe = swipe;
}
// default two-finger swipe detector
if( defaultCompFlags.globalGestures.twoFingerSwipe )
{
SwipeGestureRecognizer swipe = CreateDefaultGlobalComponent( defaultPrefabs.twoFingerSwipe );
swipe.RequiredFingerCount = 2;
swipe.OnSwipe += delegate( SwipeGestureRecognizer rec ) { RaiseOnTwoFingerSwipe( rec.StartPosition, rec.Direction, rec.Velocity ); };
defaultComponents.TwoFingerSwipe = swipe;
}
// default tap detector
if( defaultCompFlags.globalGestures.tap )
{
TapGestureRecognizer tap = CreateDefaultGlobalComponent( defaultPrefabs.tap );
tap.RequiredTaps = 0;
tap.OnTap += delegate( TapGestureRecognizer rec ) { RaiseOnTap( rec.Position, rec.Taps ); };
defaultComponents.Tap = tap;
}
// default two-finger tap detector
if( defaultCompFlags.globalGestures.twoFingerTap )
{
TapGestureRecognizer tap = CreateDefaultGlobalComponent( defaultPrefabs.twoFingerTap );
tap.RequiredFingerCount = 2;
tap.RequiredTaps = 0;
tap.OnTap += delegate( TapGestureRecognizer rec ) { RaiseOnTwoFingerTap( rec.Position, rec.Taps ); };
defaultComponents.TwoFingerTap = tap;
}
// default pinch recognizer
if( defaultCompFlags.globalGestures.pinch )
{
PinchGestureRecognizer pinch = CreateDefaultGlobalComponent( defaultPrefabs.pinch );
pinch.OnPinchBegin += delegate( PinchGestureRecognizer rec ) { RaiseOnPinchBegin( rec.GetPosition( 0 ), rec.GetPosition( 1 ) ); };
pinch.OnPinchMove += delegate( PinchGestureRecognizer rec ) { RaiseOnPinchMove( rec.GetPosition( 0 ), rec.GetPosition( 1 ), rec.Delta ); };
pinch.OnPinchEnd += delegate( PinchGestureRecognizer rec ) { RaiseOnPinchEnd( rec.GetPosition( 0 ), rec.GetPosition( 1 ) ); }; ;
defaultComponents.Pinch = pinch;
}
// default rotation recognizer
if( defaultCompFlags.globalGestures.rotation )
{
RotationGestureRecognizer rotation = CreateDefaultGlobalComponent( defaultPrefabs.rotation );
rotation.OnRotationBegin += delegate( RotationGestureRecognizer rec ) { RaiseOnRotationBegin( rec.GetPosition( 0 ), rec.GetPosition( 1 ) ); };
rotation.OnRotationMove += delegate( RotationGestureRecognizer rec ) { RaiseOnRotationMove( rec.GetPosition( 0 ), rec.GetPosition( 1 ), rec.RotationDelta ); };
rotation.OnRotationEnd += delegate( RotationGestureRecognizer rec ) { RaiseOnRotationEnd( rec.GetPosition( 0 ), rec.GetPosition( 1 ), rec.TotalRotation ); };
defaultComponents.Rotation = rotation;
}
}
void InitDefaultComponents( Finger finger )
{
ITouchFilter touchFilter = new SingleFingerFilter( finger );
DefaultComponents.FingerComponents defaultFingerComponents = defaultComponents.Fingers[finger.Index];
// touch down & up events
if( defaultCompFlags.perFinger.touch )
{
finger.OnDown += PerFinger_OnDown;
finger.OnUp += PerFinger_OnUp;
}
// setup a default motion detector using the "global" moveThreshold specified on the FingerGestures object
// this is for backward compatibility with previous 1.X versions
if( defaultCompFlags.perFinger.motion )
{
FingerMotionDetector motion = CreateDefaultFingerComponent( finger, defaultPrefabs.fingerMotion );
motion.Finger = finger;
motion.OnMoveBegin += PerFinger_OnMoveBegin;
motion.OnMove += PerFinger_OnMove;
motion.OnMoveEnd += PerFinger_OnMoveEnd;
motion.OnStationaryBegin += PerFinger_OnStationaryBegin;
motion.OnStationary += PerFinger_OnStationary;
motion.OnStationaryEnd += PerFinger_OnStationaryEnd;
defaultFingerComponents.Motion = motion;
}
// default long press gesture
if( defaultCompFlags.perFinger.longPress )
{
LongPressGestureRecognizer longPress = CreateDefaultFingerComponent( finger, defaultPrefabs.fingerLongPress );
longPress.TouchFilter = touchFilter;
longPress.OnLongPress += PerFinger_OnLongPress;
defaultFingerComponents.LongPress = longPress;
}
// setup default drag detector
if( defaultCompFlags.perFinger.drag )
{
DragGestureRecognizer drag = CreateDefaultFingerComponent( finger, defaultPrefabs.fingerDrag );
drag.TouchFilter = touchFilter;
drag.OnDragBegin += PerFinger_OnDragBegin;
drag.OnDragMove += PerFinger_OnDragMove;
drag.OnDragEnd += PerFinger_OnDragEnd;
defaultFingerComponents.Drag = drag;
}
// setup default swipe detector
if( defaultCompFlags.perFinger.swipe )
{
SwipeGestureRecognizer swipe = CreateDefaultFingerComponent( finger, defaultPrefabs.fingerSwipe );
swipe.TouchFilter = touchFilter;
swipe.OnSwipe += PerFinger_OnSwipe;
defaultFingerComponents.Swipe = swipe;
}
// setup default tap detector
if( defaultCompFlags.perFinger.tap )
{
TapGestureRecognizer tap = CreateDefaultFingerComponent( finger, defaultPrefabs.fingerTap );
tap.TouchFilter = touchFilter;
tap.RequiredTaps = 0;
tap.OnTap += PerFinger_OnTap;
defaultFingerComponents.Tap = tap;
}
}
static Finger GetFingerFromTouchFilter( GestureRecognizer recognizer )
{
SingleFingerFilter filter = recognizer.TouchFilter as SingleFingerFilter;
if( filter != null )
return filter.Finger;
return null;
}
#region Per-Finger Gestures Callbacks
void PerFinger_OnDown( Finger source )
{
RaiseOnFingerDown( source.Index, source.Position );
}
void PerFinger_OnUp( Finger source )
{
RaiseOnFingerUp( source.Index, source.Position, Time.time - source.StarTime );
}
void PerFinger_OnStationaryBegin( FingerMotionDetector source )
{
RaiseOnFingerStationaryBegin( source.Finger.Index, source.AnchorPos );
}
void PerFinger_OnStationary( FingerMotionDetector source )
{
RaiseOnFingerStationary( source.Finger.Index, source.Finger.Position, source.ElapsedStationaryTime );
}
void PerFinger_OnStationaryEnd( FingerMotionDetector source )
{
RaiseOnFingerStationaryEnd( source.Finger.Index, source.Finger.PreviousPosition, source.ElapsedStationaryTime );
}
void PerFinger_OnMoveBegin( FingerMotionDetector source )
{
RaiseOnFingerMoveBegin( source.Finger.Index, source.AnchorPos );
}
void PerFinger_OnMove( FingerMotionDetector source )
{
RaiseOnFingerMove( source.Finger.Index, source.Finger.Position );
}
void PerFinger_OnMoveEnd( FingerMotionDetector source )
{
RaiseOnFingerMoveEnd( source.Finger.Index, source.Finger.Position );
}
void PerFinger_OnDragBegin( DragGestureRecognizer source )
{
Finger finger = GetFingerFromTouchFilter( source );
RaiseOnFingerDragBegin( finger.Index, source.Position, source.StartPosition );
}
void PerFinger_OnDragMove( DragGestureRecognizer source )
{
Finger finger = GetFingerFromTouchFilter( source );
RaiseOnFingerDragMove( finger.Index, source.Position, source.MoveDelta );
}
void PerFinger_OnDragEnd( DragGestureRecognizer source )
{
Finger finger = GetFingerFromTouchFilter( source );
RaiseOnFingerDragEnd( finger.Index, source.Position );
}
void PerFinger_OnLongPress( LongPressGestureRecognizer source )
{
Finger finger = GetFingerFromTouchFilter( source );
RaiseOnFingerLongPress( finger.Index, source.Position );
}
void PerFinger_OnSwipe( SwipeGestureRecognizer source )
{
Finger finger = GetFingerFromTouchFilter( source );
RaiseOnFingerSwipe( finger.Index, source.StartPosition, source.Direction, source.Velocity );
}
void PerFinger_OnTap( TapGestureRecognizer source )
{
Finger finger = GetFingerFromTouchFilter( source );
RaiseOnFingerTap( finger.Index, source.Position, source.Taps );
}
#endregion
#endregion
#endregion
#region Finger List Data Structure
/// <summary>
/// Represent a read-only list of fingers, augmented with a bunch of utility methods
/// </summary>
public interface IFingerList : IEnumerable<Finger>
{
/// <summary>
/// Get finger in array by index
/// </summary>
/// <param name="index">The array index</param>
Finger this[int index] { get; }
/// <summary>
/// Number of fingers in the list
/// </summary>
int Count { get; }
/// <summary>
/// Get the average position of all the fingers in the list
/// </summary>
Vector2 GetAveragePosition();
/// <summary>
/// Get the average previous position of all the fingers in the list
/// </summary>
Vector2 GetAveragePreviousPosition();
/// <summary>
/// Get the average distance from each finger's starting position in the list
/// </summary>
float GetAverageDistanceFromStart();
/// <summary>
/// Find the finger with the oldest StartTime
/// </summary>
Finger GetOldest();
}
/// <summary>
/// A finger list implementation with support for write access
/// </summary>
public class FingerList : IFingerList
{
List<Finger> list;
public FingerList()
{
list = new List<Finger>();
}
public FingerList( List<Finger> list )
{
this.list = list;
}
public Finger this[int index]
{
get { return list[index]; }
}
public int Count
{
get { return list.Count; }
}
public IEnumerator<Finger> GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add( Finger touch )
{
list.Add( touch );
}
public void Clear()
{
list.Clear();
}
public delegate T FingerPropertyGetterDelegate<T>( Finger finger );
public Vector2 AverageVector( FingerPropertyGetterDelegate<Vector2> getProperty )
{
Vector2 avg = Vector2.zero;
if( Count > 0 )
{
foreach( Finger finger in list )
avg += getProperty( finger );
avg /= Count;
}
return avg;
}
public float AverageFloat( FingerPropertyGetterDelegate<float> getProperty )
{
float avg = 0;
if( Count > 0 )
{
foreach( Finger finger in list )
avg += getProperty( finger );
avg /= Count;
}
return avg;
}
static Vector2 GetFingerPosition( Finger finger ) { return finger.Position; }
static Vector2 GetFingerPreviousPosition( Finger finger ) { return finger.PreviousPosition; }
static float GetFingerDistanceFromStart( Finger finger ) { return finger.DistanceFromStart; }
public Vector2 GetAveragePosition()
{
return AverageVector( GetFingerPosition );
}
public Vector2 GetAveragePreviousPosition()
{
return AverageVector( GetFingerPreviousPosition );
}
public float GetAverageDistanceFromStart()
{
return AverageFloat( GetFingerDistanceFromStart );
}
public Finger GetOldest()
{
Finger oldest = null;
foreach( Finger finger in list )
{
if( oldest == null || ( finger.StarTime < oldest.StarTime ) )
oldest = finger;
}
return oldest;
}
}
#endregion
#region Swipe Direction
/// <summary>
/// Supported swipe gesture directions
/// </summary>
[System.Flags]
public enum SwipeDirection
{
/// <summary>
/// Moved to the right
/// </summary>
Right = 1 << 0,
/// <summary>
/// Moved to the left
/// </summary>
Left = 1 << 1,
/// <summary>
/// Moved up
/// </summary>
Up = 1 << 2,
/// <summary>
/// Moved down
/// </summary>
Down = 1 << 3,
//--------------------
None = 0,
All = Right | Left | Up | Down,
Vertical = Up | Down,
Horizontal = Right | Left,
}
/// <summary>
/// Extract a swipe direction from a direction vector and a tolerance percent
/// </summary>
/// <param name="dir">The non-constrained direction vector. Must be normalized.</param>
/// <param name="tolerance">Percentage of tolerance</param>
/// <returns>The swipe direction</returns>
public static SwipeDirection GetSwipeDirection( Vector3 dir, float tolerance )
{
float minSwipeDot = Mathf.Clamp01( 1.0f - tolerance );
if( Vector2.Dot( dir, Vector2.right ) >= minSwipeDot )
return SwipeDirection.Right;
if( Vector2.Dot( dir, -Vector2.right ) >= minSwipeDot )
return SwipeDirection.Left;
if( Vector2.Dot( dir, Vector2.up ) >= minSwipeDot )
return SwipeDirection.Up;
if( Vector2.Dot( dir, -Vector2.up ) >= minSwipeDot )
return SwipeDirection.Down;
// not a valid direction
return SwipeDirection.None;
}
#endregion
#region Single-Finger Touch Filter
/// <summary>
/// A touch filter can be used to alter the content of the input touches list initially given to each Gesture Recognizer
/// </summary>
public interface ITouchFilter
{
FingerGestures.IFingerList Apply( FingerGestures.IFingerList touches );
}
/// <summary>
/// A single-finger touch filter that:
/// - returns an list composed of its unique finger if it is contained in the the input list
/// - returns an empty list otherwise
/// This has the benefit of requiring no run-time dynamic allocations (except once at creation)
/// </summary>
public class SingleFingerFilter : ITouchFilter
{
FingerList fingerList = new FingerList();
FingerList emptyList = new FingerList();
Finger finger;
public Finger Finger
{
get { return finger; }
}
public SingleFingerFilter( Finger finger )
{
this.finger = finger;
fingerList.Add( finger );
}
public IFingerList Apply( IFingerList touches )
{
foreach( Finger touch in touches )
{
if( touch == Finger )
return fingerList;
}
return emptyList;
}
}
#endregion
#region Utils
/// <summary>
/// Check if all the fingers in the list are moving
/// </summary>
public static bool AllFingersMoving( params Finger[] fingers )
{
if( fingers.Length == 0 )
return false;
foreach( Finger finger in fingers )
{
if( finger.Phase != FingerPhase.Moved )
return false;
}
return true;
}
/// <summary>
/// Check if the input fingers are moving in opposite direction
/// </summary>
public static bool FingersMovedInOppositeDirections( Finger finger0, Finger finger1, float minDOT )
{
float dot = Vector2.Dot( finger0.DeltaPosition.normalized, finger1.DeltaPosition.normalized );
return dot < minDOT;
}
/// <summary>
/// returns signed angle in radians between "from" -> "to"
/// </summary>
public static float SignedAngle( Vector2 from, Vector2 to )
{
// perpendicular dot product
float perpDot = ( from.x * to.y ) - ( from.y * to.x );
return Mathf.Atan2( perpDot, Vector2.Dot( from, to ) );
}
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Plugins/FingerGestures/FingerGestures.cs
|
C#
|
asf20
| 64,097
|
using UnityEngine;
using System.Collections;
public class SoundPlayerScript : MonoBehaviour
{
public void PlaySound(AudioClip inClip )
{
//DontDestroyOnLoad(gameObject);
audio.PlayOneShot(inClip);
}
public void PlaySoundLoop(AudioClip inClip, float timeDelay = 0)
{
audio.loop = true;
audio.clip = inClip;
//audio.Play();
audio.PlayDelayed(timeDelay);
}
public void StopSound(string clipName)
{
if(audio.isPlaying && audio.clip.name.Equals(clipName))
audio.Stop();
}
//========================================
//
//========================================
public void Mute(bool inIsMute)
{
audio.mute = inIsMute;
}
//========================================
//
//========================================
public bool IsMute()
{
return audio.mute;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Audio/Scripts/SoundPlayerScript.cs
|
C#
|
asf20
| 845
|
public enum eSoundName {
bell,
Cancel,
chatty,
Click,
drump,
fishing_fail,
fishing_start,
fishing_start2,
fishing_succes,
fishing_wait_minigame,
open,
piyo,
piyopiyo,
shower,
sleep,
};
public enum MusicName {
Beach,
EventArea,
fever,
FishingMiniGame,
MyRoom,
Opening,
River,
SelectMap,
Shop,
};
|
zzzstrawhatzzz
|
trunk/client/Assets/Audio/Scripts/DefineAudio.cs
|
C#
|
asf20
| 321
|
using UnityEngine;
using System.Collections;
public class MusicPlayerScript : MonoBehaviour {
//========================================
//
//========================================
void Awake()
{
//DontDestroyOnLoad(gameObject);
audio.loop = true;
}
//========================================
//
//========================================
public void PlaySound(AudioClip inClip)
{
audio.clip = inClip;
audio.Play();
}
//========================================
//
//========================================
public void PauseSound()
{
audio.Pause();
}
//========================================
//
//========================================
public void Mute( bool inIsMute )
{
audio.mute = inIsMute;
}
//========================================
//
//========================================
public bool IsMute()
{
return audio.mute;
}
public void Volume(float _volume)
{
audio.volume = _volume;
}
public void Stop()
{
audio.Stop();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Audio/Scripts/MusicPlayerScript.cs
|
C#
|
asf20
| 1,089
|
using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
//using SFCLIB;
public class AvAudioManager : SingletonMono<AvAudioManager>
{
const string soundPrefab = "Prefabs/Audio/SoundPlayer";
const string musicPrefab = "Prefabs/Audio/MusicPlayer";
private Dictionary<string,AudioClip> listEffectSound = new Dictionary<string,AudioClip>();
private GameObject soundPlayerObject = null;
private SoundPlayerScript soundPlayerInterface = null;
private Dictionary<string, AudioClip> listMusic = new Dictionary<string, AudioClip>();
private GameObject musicPlayerObject = null;
private MusicPlayerScript musicPlayerInterface = null;
private AudioListener mListener = null;
void Start()
{
//Debug.LogWarning("START AUDIO MANAGAGER");
mListener = GetComponent<AudioListener>();
}
private void CheckToAddAudioListenner()
{
if(mListener == null)
{
mListener = GameObject.FindObjectOfType(typeof(AudioListener)) as AudioListener;
if (mListener == null)
{
// Debug.LogWarning("No audio listeneradd");
mListener = gameObject.AddComponent<AudioListener>();
}
}
}
//===============================================
//
//===============================================
public void Load()
{
//LoadSound();
//LoadMusic();
}
//===============================================
//
//===============================================
private void LoadSound()
{
string rootFilePathSound = Application.dataPath + "/Resources/Audio/Sound";
//
//string[] arrayFilePathSound = Directory.GetFiles( @rootFilePathSound, "*.*", SearchOption.TopDirectoryOnly ).Where(s => s.EndsWith(".mp3") || s.EndsWith(".wav"));;
string nameResources = "Resources";
foreach (string filePathSound in System.Array.FindAll(Directory.GetFiles( @rootFilePathSound, "*.*", SearchOption.AllDirectories ), PredicateEffectSoundFileMatch ))
{
int beginIndex = filePathSound.IndexOf(nameResources) + nameResources.Length + 1;
int endIndex = filePathSound.LastIndexOf(".");
string filePathForLoading = filePathSound.Substring( beginIndex, endIndex - beginIndex );
filePathForLoading = filePathForLoading.Replace("\\", "/" );
AudioClip soundClip = Resources.Load(filePathForLoading) as AudioClip;
string[] listToken = filePathForLoading.Split('/');
int length = listToken.Length;
string nameSoundClip = listToken[length - 1];
if (listToken[length - 2] != "Sound")
{
nameSoundClip = listToken[length - 2] + "_" + nameSoundClip;
}
Debug.Log("LoadSound_" + nameSoundClip);
listEffectSound.Add(nameSoundClip, soundClip);
//Debug.LogError(filePathForLoading);
}
}
//================================================================================================
//
//================================================================================================
private bool PredicateEffectSoundFileMatch(string fileName)
{
if (fileName.EndsWith(".mp3"))
return true;
if (fileName.EndsWith(".wav"))
return true;
if (fileName.EndsWith(".ogg"))
return true;
return false;
}
//===============================================
//
//===============================================
private void LoadMusic()
{
string rootFilePathSound = Application.dataPath + "/Resources/Audio/Music";
//
//string[] arrayFilePathSound = Directory.GetFiles( @rootFilePathSound, "*.*", SearchOption.TopDirectoryOnly ).Where(s => s.EndsWith(".mp3") || s.EndsWith(".wav"));;
string nameResources = "Resources";
foreach (string filePathSound in System.Array.FindAll(Directory.GetFiles( @rootFilePathSound, "*.*", SearchOption.AllDirectories ), PredicateMusicSoundFileMatch ))
{
int beginIndex = filePathSound.IndexOf(nameResources) + nameResources.Length + 1;
int endIndex = filePathSound.LastIndexOf(".");
string filePathForLoading = filePathSound.Substring( beginIndex, endIndex - beginIndex );
filePathForLoading = filePathForLoading.Replace("\\", "/" );
AudioClip soundClip = Resources.Load(filePathForLoading) as AudioClip;
string[] listToken = filePathForLoading.Split('/');
int length = listToken.Length;
string nameSoundClip = listToken[length - 1];
if (listToken[length - 2] != "Music")
{
nameSoundClip = listToken[length - 2] + "_" + nameSoundClip;
}
listMusic.Add(nameSoundClip, soundClip);
}
}
//================================================================
//
//================================================================
private bool PredicateMusicSoundFileMatch(string fileName)
{
if (fileName.EndsWith(".ogg"))
return true;
if (fileName.EndsWith(".mp3"))
return true;
return false;
}
//===============================================
//
//===============================================
public AvAudioManager()
{
//Load();
}
//===============================================
//
//===============================================
public bool PlaySound(SoundName sound, bool playLoop = false, float timeDelay = 0f)
{
return PlaySound(sound.ToString(), playLoop, timeDelay);
}
public bool PlaySound(string inName, bool playLoop, float timeDelay)
{
Debug.Log("PlaySound " + inName);
CheckToAddAudioListenner();
SoundPlayerScript player = GetSoundPlayerInterface();
if (listEffectSound.ContainsKey(inName))
{
AudioClip soundClip = listEffectSound[inName];
if (soundClip != null)
{
Debug.Log("Call PlaySound");
if(!playLoop)
player.PlaySound(soundClip);
else
player.PlaySoundLoop(soundClip, timeDelay);
}
else
{
Debug.Log("No Found Sound File");
return false;
}
}
else
{
string filePath = "Audio/Sound/" + inName;
// create
AudioClip soundClip = Resources.Load(filePath) as AudioClip;
if( soundClip != null )
{
listEffectSound.Add(inName, soundClip);
if(!playLoop)
player.PlaySound(soundClip);
else
player.PlaySoundLoop(soundClip, timeDelay);
return true;
}
Debug.LogError("No Found SOUND File Name!!!" + filePath);
return false;
}
return true;
}
public bool StopSound(SoundName soundName)
{
return StopSound(soundName.ToString());
}
public bool StopSound(string inName)
{
SoundPlayerScript player = GetSoundPlayerInterface();
if (listEffectSound.ContainsKey(inName))
{
AudioClip soundClip = listEffectSound[inName];
if(soundClip != null)
player.StopSound(inName);
}
return true;
}
//===============================================
//
//===============================================
public bool PlayMusic(MusicName music)
{
return PlayMusic(music.ToString());
}
public bool PlayMusic(string inName)
{
Debug.Log("PlayMusic " + inName);
CheckToAddAudioListenner();
MusicPlayerScript player = GetMusicPlayerInterface();
//
if (listMusic.ContainsKey(inName))
{
//Debug.LogError(player.gameObject.name);
AudioClip musicClip = listMusic[inName];
if (musicClip != null)
{
player.PlaySound(musicClip);
}
else
{
Debug.Log("No Found Music File");
return false;
}
}
else
{
string filePath = "Audio/Music/" + inName;
// create
AudioClip musicClip = Resources.Load(filePath) as AudioClip;
if( musicClip != null )
{
listMusic.Add(inName, musicClip);
player.PlaySound(musicClip);
return true;
}
Debug.LogError("No Found Music File Name!!!" + filePath);
return false;
}
return true;
}
//===============================================
//
//===============================================
public bool MuteSound( bool inIsMute )
{
SoundPlayerScript player = GetSoundPlayerInterface();
player.Mute(inIsMute);
return false;
}
//===============================================
//
//===============================================
public bool MuteMusic( bool inIsMute )
{
MusicPlayerScript player = GetMusicPlayerInterface();
player.Mute(inIsMute);
return false;
}
public void StopMusic()
{
MusicPlayerScript player = GetMusicPlayerInterface();
player.Stop();
}
public void StopMusicDelay(float _volume = 1)
{
StartCoroutine(StopMusicDelayRoutine(_volume));
}
private IEnumerator StopMusicDelayRoutine( float _volume = 1)
{
yield return new WaitForSeconds(0.05f);
MusicPlayerScript player = GetMusicPlayerInterface();
_volume -= 0.05f;
if (_volume < 0)
{
_volume = 1;
player.Stop();
player.Volume(_volume);
}
else
{
player.Volume(_volume);
StartCoroutine(StopMusicDelayRoutine(_volume));
}
}
//===============================================
//
//===============================================
public bool PauseMusic()
{
if (musicPlayerInterface != null)
{
musicPlayerInterface.PauseSound();
}
return false;
}
//===============================================
//
//===============================================
private SoundPlayerScript GetSoundPlayerInterface()
{
if (soundPlayerObject == null)
{
soundPlayerObject = GameObject.Instantiate(Resources.Load(soundPrefab)) as GameObject;
soundPlayerInterface = soundPlayerObject.GetComponent<SoundPlayerScript>();
}
return soundPlayerInterface;
}
//===============================================
//
//===============================================
private MusicPlayerScript GetMusicPlayerInterface()
{
if (musicPlayerObject == null)
{
Debug.Log("GetMusicPlayerInterface");
musicPlayerObject = GameObject.Instantiate(Resources.Load(musicPrefab)) as GameObject;
musicPlayerInterface = musicPlayerObject.GetComponent<MusicPlayerScript>();
}
return musicPlayerInterface;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Audio/Scripts/AvAudioManager.cs
|
C#
|
asf20
| 10,435
|
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
public class AudioToolEditor : ScriptableObject
{
[MenuItem("Tools/Audio/CreateAudioEnum")]
static void CreateTool()
{
string outStr = "public enum eSoundName {\n";
string nameResources = "Resources";
//effect
string rootFilePathSound = Application.dataPath + "/Resources/Audio/Sound";
foreach (string filePathSound in System.Array.FindAll(Directory.GetFiles(@rootFilePathSound, "*.*", SearchOption.AllDirectories), predicateMusicSoundFileMatch))
{
int beginIndex = filePathSound.IndexOf(nameResources) + nameResources.Length + 1;
int endIndex = filePathSound.LastIndexOf(".");
string filePathForLoading = filePathSound.Substring(beginIndex, endIndex - beginIndex);
filePathForLoading = filePathForLoading.Replace("\\", "/");
string[] listToken = filePathForLoading.Split('/');
int length = listToken.Length;
string nameSoundClip = listToken[length - 1];
if (listToken[length - 2] != "Sound")
{
nameSoundClip = listToken[length - 2] + "_" + nameSoundClip;
}
outStr += "\t" + nameSoundClip + ",\n";
}
outStr += " };\n";
//music
outStr += "public enum MusicName {\n";
rootFilePathSound = Application.dataPath + "/Resources/Audio/Music";
foreach (string filePathSound in System.Array.FindAll(Directory.GetFiles(@rootFilePathSound, "*.*", SearchOption.AllDirectories), predicateMusicSoundFileMatch))
{
int beginIndex = filePathSound.IndexOf(nameResources) + nameResources.Length + 1;
int endIndex = filePathSound.LastIndexOf(".");
string filePathForLoading = filePathSound.Substring(beginIndex, endIndex - beginIndex);
filePathForLoading = filePathForLoading.Replace("\\", "/");
string[] listToken = filePathForLoading.Split('/');
int length = listToken.Length;
string nameSoundClip = listToken[length - 1];
if (listToken[length - 2] != "Music")
{
nameSoundClip = listToken[length - 2] + "_" + nameSoundClip;
}
outStr += "\t" + nameSoundClip + ",\n";
}
outStr += " };\n";
//
Debug.Log(outStr);
FileStream fs = new FileStream(Application.dataPath + "/Scripts/Audio/DefineAudio.cs", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.Write(outStr);
sw.Flush();
sw.Close();
fs.Close();
EditorApplication.RepaintProjectWindow();
}
static bool predicateMusicSoundFileMatch(string fileName)
{
if (fileName.EndsWith(".ogg"))
return true;
if (fileName.EndsWith(".mp3"))
return true;
return false;
}
static bool predicateEffectSoundFileMatch(string fileName)
{
if (fileName.EndsWith(".mp3"))
return true;
if (fileName.EndsWith(".wav"))
return true;
return false;
}
//[MenuItem("Tools/Audio/Auto Add Click sound for button")]
//static void AutoSetSound()
//{
// AudioClip clip = Resources.Load("Audio/Sound/Click") as AudioClip;
// UIButton[] allBtn = GameObject.FindObjectsOfType<UIButton>();
// foreach(var btn in allBtn)
// {
// UIPlaySound sound = btn.GetComponent<UIPlaySound>();
// if(sound == null)
// {
// btn.gameObject.AddComponent<UIPlaySound>();
// }
// }
// UIPlaySound[] allSoundBtn = GameObject.FindObjectsOfType<UIPlaySound>();
// foreach(var soundBtn in allSoundBtn)
// {
// if(soundBtn.audioClip == null)
// {
// soundBtn.audioClip = clip;
// }
// }
//}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/Audio/Editor/AudioToolEditor.cs
|
C#
|
asf20
| 4,149
|
using UnityEngine;
using System.Collections;
public delegate void ButtonClick();
public enum DialogName
{
None,
MessageBox
}
|
zzzstrawhatzzz
|
trunk/client/Assets/UIManager/DefineUI.cs
|
C#
|
asf20
| 144
|
using UnityEngine;
using System.Collections;
public class GUIBaseDialogHandler : MonoBehaviour {
[HideInInspector]
public UIPanel uiPanel;
public void Initial()
{
Camera uiCam = GameObject.FindGameObjectWithTag("UICamera").camera;
UIAnchor[] anchors = gameObject.GetComponentsInChildren<UIAnchor>();
for (int i = 0; i < anchors.Length; i++)
{
anchors[i].uiCamera = uiCam;
}
if (uiPanel == null)
{
uiPanel = gameObject.GetComponent<UIPanel>();
}
}
public void Awake()
{
Initial();
OnInit();
}
public virtual void OnInit()
{
}
public virtual void OnBeginShow(object parameter)
{
}
public virtual void OnBeginHide(object parameter)
{
}
public virtual void OnEndHide(bool isDestroy)
{
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/UIManager/GUIBaseDialogHandler.cs
|
C#
|
asf20
| 850
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AvUIManager : SingletonMono<AvUIManager> {
private List<GUIDialogBase> listDialogs = null;
public GameObject blackBorder;
public GameObject loading;
public Camera uiCamera;
private int screenWidth=0;
private int screenHeight=0;
public UICamera GetUICamera()
{
return uiCamera.GetComponent<UICamera>();
}
// Use this for initialization
void Start()
{
Reset();
listDialogs = new List<GUIDialogBase>(GetComponentsInChildren<GUIDialogBase>());
}
// Update is called once per frame
void Update()
{
UpdateScreen();
}
public void Reset()
{
screenWidth = screenHeight = 1;
}
void UpdateScreen()
{
// if (screenWidth != Screen.width || screenHeight != Screen.height)
// {
// screenWidth = Screen.width;
// screenHeight = Screen.height;
// //Debug.LogError(screenWidth + "," + screenHeight + (((float)screenWidth / (float)screenHeight)).ToString());
// if (((float)screenWidth / (float)screenHeight) < 1.61f)
// {
// UIAnchor[] anchors = GameObject.FindObjectsOfType(typeof(UIAnchor)) as UIAnchor[];
// //Debug.LogError("BBBBBBBBBB"+anchors.Length);
// for (int i = 0; i < anchors.Length; i++)
// {
// Vector3 vec = anchors[i].autoScaleSmall;
// anchors[i].gameObject.transform.localScale = vec;
// }
// }
// else
// {
// UIAnchor[] anchors = GameObject.FindObjectsOfType(typeof(UIAnchor)) as UIAnchor[];
//
// //Debug.LogError("AAAAAAAAAAA" + anchors.Length);
// for (int i = 0; i < anchors.Length; i++)
// {
// Vector3 vec = anchors[i].autoScaleNormal;
// anchors[i].gameObject.transform.localScale = vec;
// }
// }
// }
}
public void ShowLoading()
{
blackBorder.SetActive(true);
loading.SetActive(true);
}
public void HideLoading()
{
blackBorder.SetActive(false);
loading.SetActive(false);
}
public void ShowDialog(DialogName dlgName, object param = null)
{
GUIDialogBase foundDlg = listDialogs.Find( dlg => dlg.dialogName == dlgName);
if(foundDlg == null)
{
Debug.LogError("Ko tim thay dialog:" + dlgName);
return;
}
Debug.Log("Start show dialog:" + dlgName);
if (!foundDlg.TryShow(param))
{
Debug.LogError("Ko the show dialog:" + dlgName);
}
}
public void HideDialog(DialogName dlgName, object param = null)
{
GUIDialogBase foundDlg = listDialogs.Find( dlg => dlg.dialogName == dlgName);
if(foundDlg == null)
{
Debug.LogError("Ko tim thay dialog:" + dlgName);
return;
}
Debug.Log("Hide dialog:" + dlgName);
foundDlg.Hide(param);
}
public GUIDialogBase GetDialog(DialogName dlgName)
{
return listDialogs.Find( dlg => dlg.dialogName == dlgName);
}
public void HideDialogAfterTime(DialogName dlgName,float delayTime)
{
StartCoroutine(CoroutineHideDialog(dlgName, delayTime));
}
private IEnumerator CoroutineHideDialog(DialogName dlgName,float delayTime)
{
yield return new WaitForSeconds(delayTime);
HideDialog(dlgName);
}
public void HideAllDialog()
{
if(listDialogs == null) return;
foreach(var dlg in listDialogs)
{
if(dlg != null)
dlg.Hide(null);
}
}
//
// public static void ShowDialog(GUIDialogBase panelController)
// {
// ShowDialog(panelController, null);
// }
//
// public static void ShowDialog(GUIDialogBase panelController, object parameter)
// {
// if (!panelController.TryShow(parameter))
// {
// Debug.LogError("Error:" + panelController.name);
// }
// }
//
// public static void HideDialogAfterTime(GUIDialogBase panelController,float _time)
// {
// AvUIManager.Instance.StartCoroutine(AvUIManager.Instance.CoroutineHideDialog(panelController, _time));
// }
// private IEnumerator CoroutineHideDialog(GUIDialogBase panelController,float _time)
// {
// yield return new WaitForSeconds(_time);
// HideDialog(panelController);
// }
// public static void HideDialog(GUIDialogBase panelController)
// {
// HideDialog(panelController, null);
// }
//
// public static void HideDialog(GUIDialogBase panelController, object parameter)
// {
// if(panelController == null)
// {
// Debug.LogError("tao lao bi dao roi");
// return;
// }
// panelController.Hide(parameter);
// }
public void CheckShowBorder()
{
GUIDialogBase topShow = null;
// GUIDialogBase[] controlers = gameObject.GetComponentsInChildren<GUIDialogBase>();
for (int i = 0; i < listDialogs.Count; i++)
{
if (listDialogs[i].useBlackBackground)
{
if (listDialogs[i].status == GUIDialogBase.GUIPanelStatus.Showed
|| listDialogs[i].status == GUIDialogBase.GUIPanelStatus.Showing)
{
if (topShow == null)
{
topShow = listDialogs[i];
}
else
{
if (topShow.guiControlLocation != null && listDialogs[i].guiControlLocation != null)
{
if (topShow.layer < listDialogs[i].layer)
{
topShow = listDialogs[i];
}
}
}
}
}
}
if (topShow != null && topShow.guiControlLocation != null)
{
blackBorder.SetActive(true);
blackBorder.GetComponent<UIPanel>().depth = topShow.layer-1;
}
else
{
blackBorder.SetActive(false);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/UIManager/AvUIManager.cs
|
C#
|
asf20
| 5,970
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the object's alpha.
/// </summary>
[AddComponentMenu("NGUI/Tween/Tween Alpha")]
public class TweenAlpha : UITweener
{
#if UNITY_3_5
public float from = 1f;
public float to = 1f;
#else
[Range(0f, 1f)] public float from = 1f;
[Range(0f, 1f)] public float to = 1f;
#endif
UIRect mRect;
public UIRect cachedRect
{
get
{
if (mRect == null)
{
mRect = GetComponent<UIRect>();
if (mRect == null) mRect = GetComponentInChildren<UIRect>();
}
return mRect;
}
}
[System.Obsolete("Use 'value' instead")]
public float alpha { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public float value { get { return cachedRect.alpha; } set { cachedRect.alpha = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = Mathf.Lerp(from, to, factor); }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenAlpha Begin (GameObject go, float duration, float alpha)
{
TweenAlpha comp = UITweener.Begin<TweenAlpha>(go, duration);
comp.from = comp.value;
comp.to = alpha;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
public override void SetStartToCurrentValue () { from = value; }
public override void SetEndToCurrentValue () { to = value; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenAlpha.cs
|
C#
|
asf20
| 1,639
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the camera's field of view.
/// </summary>
[RequireComponent(typeof(Camera))]
[AddComponentMenu("NGUI/Tween/Tween Field of View")]
public class TweenFOV : UITweener
{
public float from = 45f;
public float to = 45f;
Camera mCam;
public Camera cachedCamera { get { if (mCam == null) mCam = camera; return mCam; } }
[System.Obsolete("Use 'value' instead")]
public float fov { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public float value { get { return cachedCamera.fieldOfView; } set { cachedCamera.fieldOfView = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = from * (1f - factor) + to * factor; }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenFOV Begin (GameObject go, float duration, float to)
{
TweenFOV comp = UITweener.Begin<TweenFOV>(go, duration);
comp.from = comp.value;
comp.to = to;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenFOV.cs
|
C#
|
asf20
| 1,749
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the object's position.
/// </summary>
[AddComponentMenu("NGUI/Tween/Tween Position")]
public class TweenPosition : UITweener
{
public Vector3 from;
public Vector3 to;
[HideInInspector]
public bool worldSpace = false;
Transform mTrans;
UIRect mRect;
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
[System.Obsolete("Use 'value' instead")]
public Vector3 position { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public Vector3 value
{
get
{
return worldSpace ? cachedTransform.position : cachedTransform.localPosition;
}
set
{
if (mRect == null || !mRect.isAnchored || worldSpace)
{
if (worldSpace) cachedTransform.position = value;
else cachedTransform.localPosition = value;
}
else
{
value -= cachedTransform.localPosition;
NGUIMath.MoveRect(mRect, value.x, value.y);
}
}
}
void Awake () { mRect = GetComponent<UIRect>(); }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = from * (1f - factor) + to * factor; }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenPosition Begin (GameObject go, float duration, Vector3 pos)
{
TweenPosition comp = UITweener.Begin<TweenPosition>(go, duration);
comp.from = comp.value;
comp.to = pos;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenPosition.cs
|
C#
|
asf20
| 2,176
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Spring-like motion -- the farther away the object is from the target, the stronger the pull.
/// </summary>
[AddComponentMenu("NGUI/Tween/Spring Position")]
public class SpringPosition : MonoBehaviour
{
static public SpringPosition current;
/// <summary>
/// Target position to tween to.
/// </summary>
public Vector3 target = Vector3.zero;
/// <summary>
/// Strength of the spring. The higher the value, the faster the movement.
/// </summary>
public float strength = 10f;
/// <summary>
/// Is the calculation done in world space or local space?
/// </summary>
public bool worldSpace = false;
/// <summary>
/// Whether the time scale will be ignored. Generally UI components should set it to 'true'.
/// </summary>
public bool ignoreTimeScale = false;
/// <summary>
/// Whether the parent scroll view will be updated as the object moves.
/// </summary>
public bool updateScrollView = false;
public delegate void OnFinished ();
/// <summary>
/// Delegate to trigger when the spring finishes.
/// </summary>
public OnFinished onFinished;
// Deprecated functionality
[SerializeField][HideInInspector] GameObject eventReceiver = null;
[SerializeField][HideInInspector] public string callWhenFinished;
Transform mTrans;
float mThreshold = 0f;
UIScrollView mSv;
/// <summary>
/// Cache the transform.
/// </summary>
void Start ()
{
mTrans = transform;
if (updateScrollView) mSv = NGUITools.FindInParents<UIScrollView>(gameObject);
}
/// <summary>
/// Advance toward the target position.
/// </summary>
void Update ()
{
float delta = ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime;
if (worldSpace)
{
if (mThreshold == 0f) mThreshold = (target - mTrans.position).sqrMagnitude * 0.001f;
mTrans.position = NGUIMath.SpringLerp(mTrans.position, target, strength, delta);
if (mThreshold >= (target - mTrans.position).sqrMagnitude)
{
mTrans.position = target;
NotifyListeners();
enabled = false;
}
}
else
{
if (mThreshold == 0f) mThreshold = (target - mTrans.localPosition).sqrMagnitude * 0.00001f;
mTrans.localPosition = NGUIMath.SpringLerp(mTrans.localPosition, target, strength, delta);
if (mThreshold >= (target - mTrans.localPosition).sqrMagnitude)
{
mTrans.localPosition = target;
NotifyListeners();
enabled = false;
}
}
// Ensure that the scroll bars remain in sync
if (mSv != null) mSv.UpdateScrollbars(true);
}
/// <summary>
/// Notify all finished event listeners.
/// </summary>
void NotifyListeners ()
{
current = this;
if (onFinished != null) onFinished();
if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished))
eventReceiver.SendMessage(callWhenFinished, this, SendMessageOptions.DontRequireReceiver);
current = null;
}
/// <summary>
/// Start the tweening process.
/// </summary>
static public SpringPosition Begin (GameObject go, Vector3 pos, float strength)
{
SpringPosition sp = go.GetComponent<SpringPosition>();
if (sp == null) sp = go.AddComponent<SpringPosition>();
sp.target = pos;
sp.strength = strength;
sp.onFinished = null;
if (!sp.enabled)
{
sp.mThreshold = 0f;
sp.enabled = true;
}
return sp;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/SpringPosition.cs
|
C#
|
asf20
| 3,490
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the widget's size.
/// </summary>
[RequireComponent(typeof(UIWidget))]
[AddComponentMenu("NGUI/Tween/Tween Width")]
public class TweenWidth : UITweener
{
public int from = 100;
public int to = 100;
public bool updateTable = false;
UIWidget mWidget;
UITable mTable;
public UIWidget cachedWidget { get { if (mWidget == null) mWidget = GetComponent<UIWidget>(); return mWidget; } }
[System.Obsolete("Use 'value' instead")]
public int width { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public int value { get { return cachedWidget.width; } set { cachedWidget.width = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
value = Mathf.RoundToInt(from * (1f - factor) + to * factor);
if (updateTable)
{
if (mTable == null)
{
mTable = NGUITools.FindInParents<UITable>(gameObject);
if (mTable == null) { updateTable = false; return; }
}
mTable.repositionNow = true;
}
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenWidth Begin (UIWidget widget, float duration, int width)
{
TweenWidth comp = UITweener.Begin<TweenWidth>(widget.gameObject, duration);
comp.from = widget.width;
comp.to = width;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenWidth.cs
|
C#
|
asf20
| 2,063
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the widget's size.
/// </summary>
[RequireComponent(typeof(UIWidget))]
[AddComponentMenu("NGUI/Tween/Tween Height")]
public class TweenHeight : UITweener
{
public int from = 100;
public int to = 100;
public bool updateTable = false;
UIWidget mWidget;
UITable mTable;
public UIWidget cachedWidget { get { if (mWidget == null) mWidget = GetComponent<UIWidget>(); return mWidget; } }
[System.Obsolete("Use 'value' instead")]
public int height { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public int value { get { return cachedWidget.height; } set { cachedWidget.height = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
value = Mathf.RoundToInt(from * (1f - factor) + to * factor);
if (updateTable)
{
if (mTable == null)
{
mTable = NGUITools.FindInParents<UITable>(gameObject);
if (mTable == null) { updateTable = false; return; }
}
mTable.repositionNow = true;
}
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenHeight Begin (UIWidget widget, float duration, int height)
{
TweenHeight comp = UITweener.Begin<TweenHeight>(widget.gameObject, duration);
comp.from = widget.height;
comp.to = height;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenHeight.cs
|
C#
|
asf20
| 2,074
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the audio source's volume.
/// </summary>
[RequireComponent(typeof(AudioSource))]
[AddComponentMenu("NGUI/Tween/Tween Volume")]
public class TweenVolume : UITweener
{
#if UNITY_3_5
public float from = 1f;
public float to = 1f;
#else
[Range(0f, 1f)] public float from = 1f;
[Range(0f, 1f)] public float to = 1f;
#endif
AudioSource mSource;
/// <summary>
/// Cached version of 'audio', as it's always faster to cache.
/// </summary>
public AudioSource audioSource
{
get
{
if (mSource == null)
{
mSource = audio;
if (mSource == null)
{
mSource = GetComponent<AudioSource>();
if (mSource == null)
{
Debug.LogError("TweenVolume needs an AudioSource to work with", this);
enabled = false;
}
}
}
return mSource;
}
}
[System.Obsolete("Use 'value' instead")]
public float volume { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Audio source's current volume.
/// </summary>
public float value
{
get
{
return audioSource != null ? mSource.volume : 0f;
}
set
{
if (audioSource != null) mSource.volume = value;
}
}
protected override void OnUpdate (float factor, bool isFinished)
{
value = from * (1f - factor) + to * factor;
mSource.enabled = (mSource.volume > 0.01f);
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenVolume Begin (GameObject go, float duration, float targetVolume)
{
TweenVolume comp = UITweener.Begin<TweenVolume>(go, duration);
comp.from = comp.value;
comp.to = targetVolume;
return comp;
}
public override void SetStartToCurrentValue () { from = value; }
public override void SetEndToCurrentValue () { to = value; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenVolume.cs
|
C#
|
asf20
| 1,962
|