Unity3D範例之3.DragRigidbody


 DragRigidbody.cs

using UnityEngine;
using System.Collections;


public class DragRigidbody : MonoBehaviour {
 public float spring;
 public float damper;
 public float drag;
 public float angularDrag;
 public float distance;
 public bool attachToCenterOfMass; 

 private SpringJoint springJoint;
 private Rigidbody body;

 // Use this for initialization

 void Start () {
     spring = 50.0f;
     damper = 5.0f;
     drag = 10.0f;
     angularDrag = 5.9f;
     distance = 0.2f;
     attachToCenterOfMass = false;
 }

 // Update is called once per frame
 void Update () {
  if(!Input.GetMouseButtonDown(0)) return;  

  Camera mainCamera = FindCamera();
  RaycastHit hit;  
  //檢測滑鼠按鍵是否點擊 
  if(!Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition),out hit,100)) return;
  //是否有點擊到剛性物體或剛性物體可被物理控制 
  if(!hit.rigidbody||hit.rigidbody.isKinematic) return; 
  if(!springJoint){ //彈性物體是否存在
   //新增一個名稱為"Rigidbody dragger"的遊戲物件
   GameObject go = new GameObject("Rigidbody dragger");  
   body = (Rigidbody)go.AddComponent("Rigidbody");
   springJoint = (SpringJoint)go.AddComponent("SpringJoint");
   body.isKinematic = true;
  }
  springJoint.transform.position = hit.point;
  if(attachToCenterOfMass){
    Vector3 anchor = transform.TransformDirection(hit.rigidbody.centerOfMass)+
                     hit.rigidbody.transform.position;
    anchor = springJoint.transform.InverseTransformPoint(anchor);
    springJoint.anchor = anchor;
  }else{
    springJoint.anchor = Vector3.zero;
  }

  springJoint.spring = spring;
  springJoint.damper = damper;
  springJoint.maxDistance = distance;
  springJoint.connectedBody = hit.rigidbody;
  //執行協程(執行緒),處理拖行物體
  StartCoroutine("DragObject",hit.distance);

 }

 IEnumerator DragObject(float distance){
  float oldDrag = springJoint.connectedBody.drag;
  float oldAngularDrag = springJoint.connectedBody.angularDrag;
  springJoint.connectedBody.drag = drag; 
  springJoint.connectedBody.angularDrag = angularDrag;
  Camera mainCamera = FindCamera();
  while(Input.GetMouseButton(0)){
   Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
   springJoint.transform.position = ray.GetPoint(distance);  
   yield return 0;

  }

  if(springJoint.connectedBody){
   springJoint.connectedBody.drag = oldDrag;
   springJoint.connectedBody.angularDrag = oldAngularDrag;
   springJoint.connectedBody = null;

  }

 }

 //取得主要攝影機
 Camera FindCamera(){
   if(camera){
    return camera;
   }else{
    return Camera.main;  //回傳標註為MainCamera的攝影機物件
   }
 }

}

留言

這個網誌中的熱門文章

C# 調用 C/C++ DLL 資料型態之對應

在Ubuntu上安裝EZ100PU晶片讀卡機