unity3d雜錄【1】

f_DeltaTime值。 //本身計算每一幀時間
html

float f_LastFrameRealtime;

void Start()
{
f_LastFrameRealtime = Time.realtimeSinceStartup ;
}

void Update()
{
float f_DeltaTime = Time.realtimeSinceStartup - f_LastFrameRealtime;
f_LastFrameRealtime = Time.realtimeSinceStartup ;
}

 


(2) mecanim系統中 muscle能夠控制角色各部位擺動幅度等, 速度爲負,動畫倒着播放android

Vector3 wantedDir = (target.position- anim.rootPosition).normalized; //想要到達的面向
Vector3 currentDir = anim.rootRotation * Vector3.forward;//當前面向
if(Vector3.Dot(currentDir, wantedDir) > 0){//dot cos值>0既在currentDir的前半圓
anim.SetFloat("Direction", Vector3.Cross(currentDir, wantedDir).y, .25f, Time.deltaTime); 這裏在currentDir右邊既爲正.
//cross叉乘 ,叉乘向量的y值既,在xz面中,wantedDir在currentdir 的哪一個位置,1到-1之間,左手座標系,四指指向原向量,四指彎曲指向目標向量,大拇指所指方向既爲正
}else{
anim.SetFloat("Direction",Vector3.Cross(currentDir,wantedDir).y > 0 ? 1 : -1, .25f, Time.deltaTime);
}

col.Move(anim.deltaPosition);//animator動畫的幀位置
transform.rotation = anim.rootRotation;//根旋轉量

animator anystate 優先級最高,只要設定了變量,爲真,立刻執行
setikposition 能夠調製角色不一樣部位的單獨控制,分建不一樣的層

//修改攝像機的cullingMask web

int oldMask = camera.cullingMask;
// change mask
camera.cullingMask = (1 << LayerMask.NameToLayer("TransparentFX")) | (1 << LayerMask.NameToLayer("OtherLayer"));
// do something
// ...
// restore mask
camera.cullingMask = oldMask;

  

Profiler 探查窗口 能夠查看cpu使用率等
RenderTexture 攝像機 製做舞臺效果編輯器

組件右上角,copy component 能夠粘貼屬性,或複製。ide

meshrenderer不激活,則物體不顯示,但仍然存在,能夠碰到函數

在編輯器選中須要添加碰撞的UITexture對象,給該對象必需要先賦予Texture,直接操做「Alt+Shift+C」,
NGUI會給你計算出一個適合於當前對象的BoxCoillder。若是說該對象已經有一個BoxCoillder,那NGUI會調整它的大小以適應UITexture的大小。
剩下的就是按照本身的須要調整順序關係。
右鍵向深度高的,左鍵向深度低的post

start裏面使用協同,能夠不用update而按時間執行好比動畫

void Start(){
StartCoroutine(GoToSleep());
}
IEnumerator GoToSleep(){
yield return new WaitForSeconds(startCheckInSeconds);

while( sth){
yield return new WaitForSeconds(checkEverySeconds);
}
do last sth;
finish;
}

  

shader 中加Cull off 不遮擋,背部也能看到ui

InfiniLearning Game Development With Unity 3D.rar 第六章講鋼體,cloth ragdollthis

camera.layerCullDistances 設置各層的fardistance ,能夠把小物體放在合適的層,設置distance,離相機多遠時不顯示小物體

使用協同作時間冷卻

direction = transform.TransformDirection(direction);

direction原本是世界座標vector3, TransformDirection(裏面基於自身local座標系)將裏面轉爲世界座標值.

//攝像機按鼠標左右移動旋轉

xAngl += Input.GetAxis ("Mouse X") * xSpeed * 0.02f;
Quaternion camRot = Quaternion.Euler (yAngl, xAngl, 0);
cam.rotation = camRot;

  

/** 按固定速度旋轉
var target: Transform;
var rotateSpeed=30.0;
var t=float;
var q:Quaternion;

var wantedRotation=Quaternion.FromToRotation(transform.position,target.position);
t=rotateSpeed/Quaternion.Angle(transform.rotation,wantedRotation)*Time.deltaTime;
q=Quaternion.Slerp(transform.rotation, target.rotation,t);
transform.rotation=q;
**/

  



mecanim系統中 ,選中IK PASS OnAnimatorIK()裏的對應層的IK動做才能起做用
anystate表明全部狀態都能進入當條件爲真時

Quaternion.SetLookRotation(z軸朝向的位置,y軸朝向的位置) 返回Quaternion;

當你啓動Unity按住ALT鍵時,可讓你選擇所需打開項目。(不然它將嘗試更新最後打開的項目)

請問有沒有遇到過 添加了第三方插件SDK以後 若是手機處於待機狀態的時候 就會退出APP的狀況的呢
北京-KL-程序(1557899269) 下午 18:11:28
有人提過改xml
android:configChanges="orientation|keyboardHidden|navigation|screenSize"


計算那麼角色速度角速度。
flota speed = agent.desiredVelocity.magnitude;
Vector3 velocity = Quaternion.Inver(trnasform.rotation) * agent.desiredVelocity;
float angle = Mathf.Atan2(velocity.x, velocity.z)* 180.0f/3.14159f;
//當有rootMotion的時候OnAnimatorMove回調函數
agent.velocity =animator.deltaPosition/Time.deltatime
transform.rotation = animator.rootRotation;


By default Unity compresses all textures when importing. This can be turned off in the Preferences for faster workflow. But when building a game, all not-yet-compressed textures will be compressed.
默認狀況下,Unity會在導入時對紋理進行壓縮,爲了加速工做,你能夠在Preferences裏關閉該功能,可是當編譯遊戲時,全部還沒有被壓縮紋理都將被從新壓縮。

Guitext 屏幕座標,x:0-1 y:0-1


歐拉角限制 繞y和z 爲-180到180,即左右轉,和左右傾斜 x爲-90到90即先後傾斜

Layer的用法

LayerMask.NameToLayer("Ground");  // 經過名字獲取layer

 

物理攝像頭取色(WebCamTexture)

Texture2D exactCamData() {  

    // get the sample pixels  

    Texture2D snap = new Texture2D((int)detectSize.x, (int)detectSize.y);  

    snap.SetPixels(webcamTexture.GetPixels((int)detectStart.x, (int)detectStart.y, (int)detectSize.x, (int)detectSize.y));  

    snap.Apply();  

    return snap;  

}

  

保存截圖:System.IO.File.WriteAllBytes(Application.dataPath + "/test.png", exactCamData().EncodeToPNG());

動畫編碼

http://www.cnblogs.com/lopezycj/archive/2012/05/18/Unity3d_AnimationEvent.html

http://game.ceeger.com/Components/animeditor-AnimationEvents.html

http://answers.unity3d.com/questions/8172/how-to-add-new-curves-or-animation-events-to-an-im.html

調試技巧(Debug)

能夠在OnDrawGizmos函數來進行矩形區域等,達到調試的目的,請參考NGUI中的UIDraggablePanel.cs文件中的那個函數實現。

#if UNITY_EDITOR
	/// <summary>
	/// Draw a visible orange outline of the bounds.
	/// </summary>
	void OnDrawGizmos ()
	{
		if (mPanel != null)
		{
			Bounds b = bounds;
			Gizmos.matrix = transform.localToWorldMatrix;
			Gizmos.color = new Color(1f, 0.4f, 0f);
			Gizmos.DrawWireCube(new Vector3(b.center.x, b.center.y, b.min.z), new Vector3(b.size.x, b.size.y, 0f));
		}
	}
#endif

  Lerp函數的使用場景

// Set the health bar's colour to proportion of the way between green and red based on the player's health.
healthBar.material.color = Color.Lerp(Color.green, Color.red, 1 - health * 0.01f);

  在特定位置播放聲音

// Play the bomb laying sound.
AudioSource.PlayClipAtPoint(bombsAway,transform.position);

  經過腳本修改shader中uniform的值

//shader的寫法
Properties {
    ...
    disHeight ("threshold distance", Float) = 3
}
 
SubShader {
    Pass {
        CGPROGRAM
        #pragma vertex vert  
        #pragma fragment frag 
        ...
        uniform float disHeight;
        ...	
// ===================================
// 修改shader中的disHeight的值
gameObject.renderer.sharedMaterial.SetFloat("disHeight", height);

  雙擊事件

void OnGUI() {
    Event Mouse = Event.current;
    if ( Mouse.isMouse && Mouse.type == EventType.MouseDown && Mouse.clickCount == 2) {
        print("Double Click");
    }
}

  RootAnimation中移動的腳本處理

class RootControl : MonoBehaviour {
	void OnAnimatorMove() {
		Animator anim = GetComponent<Animator>();
		if(anim) {
			Vector3 newPos = transform.position;
			newPos.z += anim.GetFloat("Runspeed") * Time.deltaTime;
			transform.position = newPos;
		}
	}
}

  BillBoard效果(廣告牌效果,或者向日葵效果,使得對象重視面向攝像機

public class BillBoard : MonoBehaviour {
	// Update is called once per frame
	void Update () {
		transform.LookAt(Camera.main.transform.position, -Vector3.up);
	}
}

  script中的屬性編輯器(Property Drawers),還能夠自定義屬性編輯器

public class Example : MonoBehaviour {
    public string playerName = "Unnamed";

    [Multiline]
    public string playerBiography = "Please enter your biography";

    [Popup ("Warrior", "Mage", "Archer", "Ninja")]
    public string @class = "Warrior";

    [Popup ("Human/Local", "Human/Network", "AI/Easy", "AI/Normal", "AI/Hard")]
    public string controller;

    [Range (0, 100)]
    public float health = 100;

    [Regex (@"^(?:\d{1,3}\.){3}\d{1,3}$", "Invalid IP address!\nExample: '127.0.0.1'")]
    public string serverAddress = "192.168.0.1";

    [Compact]
    public Vector3 forward = Vector3.forward;

    [Compact]
    public Vector3 target = new Vector3 (100, 200, 300);

    public ScaledCurve range;
    public ScaledCurve falloff;

    [Angle]
    public float turnRate = (Mathf.PI / 3) * 2;
}

  debug下畫線

  Debug.DrawLine (Vector3.zero, new Vector3 (10, 0, 0), Color.red);  

 

獲取AnimationCurve的時長

_curve.keys[_curve.length-1].time;

  使得腳本可以在editor中實時反映:

在腳本前加上:[ExecuteInEditMode], 參考UISprite。

    NGUI類關係圖

//在2秒內使顏色變黑。

function Update ()

{
    light.color-= Color.white / 2.0 * Time.deltaTime;
}
//在2個顏色之間來回插值光源顏色。
var duration =1.0;
var color0 = Color.red;
var color1 = Color.blue;
function Update ()

{
   //設置光源顏色
   var t = Mathf.PingPong (Time.time, duration) / duration;
    light.color= Color.Lerp (color0, color1, t);
}

  

 

 

//隨時間改變光照強度

var duration = 1.0;
function Update()

{
   //餘弦理論
   var phi = Time.time / duration * 2 * Mathf.PI;
   //獲取餘弦,並將範圍從-1~1變爲0~1
   var amplitude = Mathf.Cos( phi ) * 0.5 + 0.5;
   //設置光的顏色
   light.intensity = amplitude;
}

  

 

描述:光源的範圍。
即便光源關閉了attenuate,它仍是隻影響在它範圍內的物體。

//在原始範圍與原始範圍通常處變換光照範圍
var duration =3.0;
private var originalRange : float;
originalRange = light.range;
function Update()

{
    var amplitude = Mathf.PingPong( Time.time,duration );
    //將0..持續時間改成0.5..1範圍
    amplitude = amplitude / duration * 0.5 + 0.5;
    //設置光照範圍
    light.range = originalRange * amplitude;
}

  

var renderMode :LightRenderMode

描述:如何渲染該光源?此處能夠是LightRenderMode.Auto,LightRenderMode.ForceVertex 或LightRenderMode.ForcePixel。像素光渲染比較慢可是看起來較好,尤爲是對那些沒有較高面數的幾何體。一些效果(例如凹凸)只會在像素光照下顯示。

 

Cancellnvoke():void

描述:取消全部在這個MonoBehaviour上調用

Cancellvoke(methodName:string):void

描述:撤銷該行爲中名爲methodName的全部調用。

Invoke  and    InvokeRepeating

 

描述:OnBecameInvisible函數在渲染上的腳本。OnBecameVisible和OnBecameInvisible能夠用於只須要在須要在物體可見時才進行的計算。
//當它不可見時禁用這個行爲
function OnBecameInvisible()

{
   enabled=false;
}

OnBecameInvisible能夠是一個coroutine,簡單地在這個函數中使用yield語句。當在編輯器中運行時,場景試圖相機也會致使這個函數被調用。

 

 

functiononParticleCollision(other:GameObject):void

描述:當一個粒子碰到一個碰撞器時OnParticleCollision被調用。
這個能夠在遊戲物體被粒子擊中時應用傷害到它的上面,這個消息被髮送到全部附加到
WorldParticleCollider 的腳本上和被擊中的Collider上,這個消息只有當你在
WorldParticleCollider檢視面板中啓用了sendCollisionMessage時纔會被髮送。
//應用力到全部被粒子擊中的剛體上

 

functionOnParticleCollison(other:GameObject)

{
   varbody=other.rigidbody;
   if(body)

  {
    var direction=other.transform.position+transform.position;
    direction=direction.normalized;
    body.AddForce(direction*5);
   }
}

  

OnParticleCollision能夠是一個coroutine,簡單地在這個函數中使用yield語句。

 

function OnpostRender():void


描述:OnPostRender在相機渲染場景以後調用。
只有腳本被附加到相機上時纔會調用這個函數。OnPostRender能夠是一個coroutine,簡單地在這個函數中使用yield語句。
OnPostRender在相機渲染完全部它的物體以後被調用。若是你想在全部相機和GUI被渲染以後作一些事情,使用WaitForEndFramecoroutine
參見:OnPreRender,WaitForEndOfFrame
//當附加到機時,將消除
//相機紋理的alpha通道爲純白色
//若是你有一個渲染紋理並想將它顯示在GUI上時可使用這個函數

private varmat:Material;
function OnPostRender()

{
    //建立一個只渲染白色到alpha通道的着色器
   if(mat)
    {
      mat=newMaterial(「Shader Hidden SetAlpha」+)
    「SubShader{「+」pass{」+」ZTest Always Cull off ZwriteOff」+」ColorMaskA」+」Color  (1,1,1,1)」+」}」+」}」+」}」);
    }
}

  

 

// 用上述着色器繪製一個全屏四邊形

GL.PushMatrix();
GL.LoadOrtho();
for(var i=0;i<mat.pssCount;++i)

{
  mat.SetPass(i);
  GL.Begin(GL.QUADS);
  GL.Vertex3(0,0,0.1);
  GL.Vertex3(1,0,0.1);
  GL.Vertex3(1,1,0.1);
  GL.Vertex3(0,1,0.1);
  GL.End();
 }
 GL.PopMatrix();
}

  

 

function OnRender():void

描述:OnpreRender在相機開始渲染場景以前調用。
只用腳本被附加到相機上時纔會調用這個函數。
注意如是果你在這裏改變了相機的視野參數(例如fieldOfView),它們將影響下一幀。用OnPreCull代替。

 

強烈建議使用DestroyImmediate 代替 Destroy

 

OnCollisionEnter(collision:Collision)

{
    //調試繪製全部的接觸點和法線
    for(varcontact:ContacePoint in collision.contacts)

   {
        Debug.DrawRay(contact.point,contact.normal,color.white);
    }
    //若是碰撞物體有較大的衝擊就播放聲音
   if(collision.relativeVelocity.magnitude.2)
    Audio.Play();
 }

  

U3D屏幕截圖 

function ScreenshotEncode()
{
// wait for graphics to render
yield WaitForEndOfFrame();

// create a texture to pass to encoding
var texture:Texture2D = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false);

// put buffer into texture
texture.ReadPixels(Rect(0.0, 0.0, Screen.width, Screen.height), 0.0, 0.0);
texture.Apply();

// split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy
yield;

// create our encoder for this texture
var encoder:JPGEncoder = new JPGEncoder(texture, 75.0);

// encoder is threaded; wait for it to finish
while(!encoder.isDone)
yield;

// save our test image (could also upload to WWW)
File.WriteAllBytes(Application.dataPath + "/../testscreen-" + count + ".jpg", encoder.GetBytes());
count++;
}


//簡便方法看下面:

function OnMouseDown() {
Application.CaptureScreenshot("Screenshot.png");
}

  

Unity腳本週期關係  

 

 

PS:摘抄自互聯網 有刪改

http://blog.csdn.net/stalendp/article/details/17114135

http://dearymz.blog.163.com/blog/static/20565742013341916919/

http://angeson1987.blog.163.com/blog/static/162590090201062931129143/

http://cl314413.blog.163.com/blog/static/1905079762012757504225/

相關文章
相關標籤/搜索