[Unity] 常用技巧收集
Unity 屏幕旋转
void Update () { //处理横向两个方向旋转 if(Input.deviceOrientation == DeviceOrientation.LandscapeLeft) { if (Screen.orientation != ScreenOrientation.LandscapeLeft) { Screen.orientation = ScreenOrientation.LandscapeLeft; } }else if(Input.deviceOrientation == DeviceOrientation.LandscapeRight) { if (Screen.orientation != ScreenOrientation.LandscapeRight) { Screen.orientation = ScreenOrientation.LandscapeRight; } }else //处理纵向两个方向的旋转 if(Input.deviceOrientation == DeviceOrientation.Portrait) { if (Screen.orientation != ScreenOrientation.Portrait) { Screen.orientation = ScreenOrientation.Portrait; } }else if(Input.deviceOrientation == DeviceOrientation.PortraitUpsideDown) { if (Screen.orientation != ScreenOrientation.PortraitUpsideDown) { Screen.orientation = ScreenOrientation.PortraitUpsideDown; } } }
Unity 镜头拉近效果(带缓冲)
var target : Transform; var distance : float = 3.0; var height : float = 1.0; var damping : float = 5.0; var smoothRotation : boolean = true; var rotationDamping : float = 10.0; var targetLookAtOffset : Vector3; // allows offsetting of camera lookAt, very useful for low bumper heights var bumperDistanceCheck : float = 2.5; // length of bumper ray var bumperCameraHeight : float = 1.0; // adjust camera height while bumping var bumperRayOffset : Vector3; // allows offset of the bumper ray from target origin function FixedUpdate() { var wantedPosition = target.TransformPoint(0, height, -distance); // check to see if there is anything behind the target var hit : RaycastHit; var back = target.transform.TransformDirection(-1 * Vector3.forward); // cast the bumper ray out from rear and check to see if there is anything behind if (Physics.Raycast(target.TransformPoint(bumperRayOffset), back, hit, bumperDistanceCheck)) { // clamp wanted position to hit position wantedPosition.x = hit.point.x; wantedPosition.z = hit.point.z; wantedPosition.y = Mathf.Lerp(hit.point.y + bumperCameraHeight, wantedPosition.y, Time.deltaTime * damping); } transform.position = Vector3.Lerp(transform.position, wantedPosition, Time.deltaTime * damping); var lookPosition : Vector3 = target.TransformPoint(targetLookAtOffset); if (smoothRotation) { var wantedRotation : Quaternion = Quaternion.LookRotation(lookPosition - transform.position, target.up); transform.rotation = Quaternion.Slerp(transform.rotation, wantedRotation, Time.deltaTime * rotationDamping); } else { transform.rotation = Quaternion.LookRotation(lookPosition - transform.position, target.up); } }
Untiy 动画加速
for (var state : AnimationState in animation) { state.speed = 0.5; }
Unith3D判断物体是否在视角内
public var isRendering:boolean=false; private var lastTime:float=0; private var curtTime:float=0; function Update() { isRendering=curtTime!=lastTime?true:false; lastTime=curtTime; } function OnWillRenderObject() { curtTime=Time.time; }
如何判断Unity3D角色动作播放结束
bool AnimationStillPlaying( string animationName ) { return _animation.IsPlaying(animationName) && _animation[animationName].normalizedTime<1.0f; } normalizedTime: 范围0 -- 1, 0是动作开始,1是动作结束
利用Quaternion.LookRotation API 将旋转矩阵转换成四元数
Quaternion.LookRotation private static Quaternion QuaternionLookRotation(Vector3 forward, Vector3 up) { forward.Normalize(); Vector3 vector = Vector3.Normalize(forward); Vector3 vector2 = Vector3.Normalize(Vector3.Cross(up, vector)); Vector3 vector3 = Vector3.Cross(vector, vector2); var m00 = vector2.x; var m01 = vector2.y; var m02 = vector2.z; var m10 = vector3.x; var m11 = vector3.y; var m12 = vector3.z; var m20 = vector.x; var m21 = vector.y; var m22 = vector.z; float num8 = (m00 + m11) + m22; var quaternion = new Quaternion(); if (num8 > 0f) { var num = (float)Math.Sqrt(num8 + 1f); quaternion.w = num * 0.5f; num = 0.5f / num; quaternion.x = (m12 - m21) * num; quaternion.y = (m20 - m02) * num; quaternion.z = (m01 - m10) * num; return quaternion; } if ((m00 >= m11) && (m00 >= m22)) { var num7 = (float)Math.Sqrt(((1f + m00) - m11) - m22); var num4 = 0.5f / num7; quaternion.x = 0.5f * num7; quaternion.y = (m01 + m10) * num4; quaternion.z = (m02 + m20) * num4; quaternion.w = (m12 - m21) * num4; return quaternion; } if (m11 > m22) { var num6 = (float)Math.Sqrt(((1f + m11) - m00) - m22); var num3 = 0.5f / num6; quaternion.x = (m10+ m01) * num3; quaternion.y = 0.5f * num6; quaternion.z = (m21 + m12) * num3; quaternion.w = (m20 - m02) * num3; return quaternion; } var num5 = (float)Math.Sqrt(((1f + m22) - m00) - m11); var num2 = 0.5f / num5; quaternion.x = (m20 + m02) * num2; quaternion.y = (m21 + m12) * num2; quaternion.z = 0.5f * num5; quaternion.w = (m01 - m10) * num2; return quaternion; }
Unity3D判断场景是否加载完成
加载场景时要用 public static AsyncOperation async; async = Application.LoadLevelAsync(“SelectCarModelScreen”); 在加载场景里写 if (MainInterfaceGUIScript.async.isDone == false) { //________没 有加载完要做的事情如Logo__________________________ } else { //全部加载完成后显示的东东。。 } 说明一点这种方法消耗性能哦
物体运动到指定位置
int smooth = 2; Quaternion target = Quaternion.Euler(0, 0, 0);//目标 // Dampen towards the target rotation transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth); 《《《《《《《《《《《《《《鼠标左键地形 物体移动至点击位置》》》》》》》》》》》》》 var moveSpeed:int=5;//player移动速度 var player:Transform;//定义一个人物的Transform private var endposition : Vector3; function Start() { endposition = player.transform.position; } function Update () { if(Input.GetButtonUp("LeftMouse")){ //LeftMouse是在inputManager中设置的,左键值为mouse 0 PlayerMove(); } var targetposition=player.TransformPoint(Vector3(0,48.8,-30)); transform.position=targetposition;//相机的目标位置,这两句代码的作用是让人物一直处于相机的视野下 if(endposition != player.transform.position){ player.position=Vector3.MoveTowards(player.position,endposition,Time.deltaTime*moveSpeed); } } function PlayerMove() { var cursorScreenPosition:Vector3=Input.mousePosition;//鼠标在屏幕上的位置 var ray:Ray=Camera.main.ScreenPointToRay(cursorScreenPosition);//在鼠标所在的屏幕位置发出一条射线(暂名该射线为x射线) var hit:RaycastHit; if(Physics.Raycast(ray,hit)){ if(hit.collider.gameObject.tag=="Terrain"){//设置地形Tag为Terrain endposition = hit.point; } } }
射线测试+使用手势判断是否触碰了某物体
using unityEngine; using System.Collections; public class Lu : MonoBehaviour { public Camera cam; // We need to actually hit an object RaycastHit hitt = new RaycastHit(); // Use this for initialization void Start() { } // Update is called once per frame void Update() { Ray ray = cam.ScreenPointToRay(Input.mousePosition); Physics.Raycast(ray, out hitt, 100); // Debug.DrawLine(cam.transform.position, ray.direction,Color.red); if (null != hitt.transform) { print(hitt.point);//鼠标点击的坐标 } } } |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| 必须给物体添加碰撞器,比如Box Collider 然后在Update中检测手势,此处假设为手指在屏幕上移动 主相机的视角(Camera.main)从手指移动处(Input.GetTouch(0).position)发射射线,设置射线发射距离。 当射线碰撞到了带有碰撞器的物体,就会存储该物体的信息。 [csharp] view plaincopy void Update(){ if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved){ Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch(0).position); //hit用来存储碰撞物体的信息 RaycastHit hit; //ray表示射线,hit存储物体的信息,1000为设定射线发射的距离 if(Physics.Raycast (ray, out hit, 1000)){ print(hit.transform.name.ToString()); } } }
实例来创建对象
//Simple Instantiation of a Prefab at Start var thePrefab : GameObject; function Start () { var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation); } 建立JAVA,把代码拖入到空GameJect上,然后把Prefab拖入到公共变量上,就可以了
声音播放 坐标转换
var cAudio:AudioClip; function Update(){ } function OnMouseDown () { var screenSpace = Camera.main.WorldToScreenPoint(transform.position); var offset = transform.position - Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x,transform.position.y, screenSpace.z)); while (Input.GetMouseButton(0)){ var curScreenSpace = Vector3(Input.mousePosition.x, transform.position.y, screenSpace.z); var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset; if(curPosition!=transform.position){ audio.Stop(); audio.clip = cAudio; audio.Play(); } transform.position = curPosition; yield; } }
射线 (之鼠标点击的坐标)
using UnityEngine; using System.Collections; public class Lu : MonoBehaviour { public Camera cam; // We need to actually hit an object RaycastHit hitt = new RaycastHit(); // Use this for initialization void Start() { } // Update is called once per frame void Update() { Ray ray = cam.ScreenPointToRay(Input.mousePosition); Physics.Raycast(ray, out hitt, 100); // Debug.DrawLine(cam.transform.position, ray.direction,Color.red); if (null != hitt.transform) { print(hitt.point);//鼠标点击的坐标 } } }
拖拽物体的脚本
function OnMouseDown () { var screenSpace = Camera.main.WorldToScreenPoint(transform.position); var offset = transform.position - Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z)); while (Input.GetMouseButton(0)) { var curScreenSpace = Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z); var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset; transform.position = curPosition; yield; } }
用指定图片替换鼠标指针
//用指定图片替换鼠标指针 var mouse:Texture; function Update(){ Screen.showCursor=false;//隐藏鼠标指针 } function OnGUI{ var msPos=Input.mousePosition;//鼠标的位置 GUI.DrawTexture(Rect(msPos.x,Screen.height-msPos.y,20,20),mouse); }
Unity 字体描边
private void MakeStroke(Rect position,string txtString,Color txtColor,Color outlineColor,int outlineWidth ) { position.y-= outlineWidth; GUI.color=outlineColor; GUI.Label(position, txtString); position.y+=outlineWidth*2; GUI.Label(position, txtString); position.y-=outlineWidth; position.x-=outlineWidth; GUI.Label(position, txtString); position.x+=outlineWidth*2; GUI.Label(position, txtString); position.x-=outlineWidth; GUI.color=txtColor; GUI.Label(position, txtString); }
调用外部的EXE和载入关卡
using unityEngine; using System.Collections; public class openexe: MonoBehaviour { // Use this for initialization void Start () { System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo(); Info.FileName = "C:\\Program Files\\Autodesk\\3dsMax8\\3dsmax.exe"; System.Diagnostics.Process.Start(Info); } // Update is called once per frame void Update () { } } -----------------载入关卡-------------- function OnGUI () { if (GUI.Button(new Rect(400,400,100,20),"Start")) { Application.LoadLevel(1); } }