2017-08-30 125 views
1

我試圖在c#中找到任何一個例子來選擇一個物體放入玩家的手部位置並四處移動。然後當按鈕被釋放時,該對象被丟棄。我在一個統一的論壇中找到了一個例子,但是它在javascript中,我怎樣才能在C#中實現這一點?撿起和移動物體

這是我找到的代碼,但我需要搶當按鈕被點擊並且玩家需要在物體的前面時。

#pragma strict 

var TheSystem : Transform; 
var Distance : float; 
var MaxDistance : float = 10; 

function Update() { 



     var hit : RaycastHit; 
    if (Physics.Raycast (TheSystem.transform.position, TheSystem.transform.TransformDirection(Vector3.forward), hit)) 
    {  
     if(hit.transform.gameObject.tag == "sword2"){ 


     Distance = hit.distance; 
     if (Distance < MaxDistance){ 


      if (Input.GetKeyDown(KeyCode.E)) { 
       // show 
      renderer.enabled = true; 
      Destroy (GameObject.FindWithTag("sword2")); 
        } 

      if (Input.GetKeyDown(KeyCode.Backspace)) { 
      // hide 
      renderer.enabled = false; 
       } 

      } 
     } 
    } 
    } 

我有這個c#示例,但它拖動。我需要找得到它,當我搶到的主攝像頭的空對象的方式,我需要改變,以搶插在播放器位置的空對象

using UnityEngine; 
using System.Collections; 

public class drag : MonoBehaviour { 
float distance = 10; 
void OnMouseDrag(){ 
    Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance); 
    Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition); 
    transform.position = objPosition; 
} 
} 
+1

你在哪裏試圖「翻譯」這個?你遇到了什麼問題? – UnholySheep

回答

1

爲了達到你所擁有的記住有必要結合許多事情。

  1. 觸發檢測當玩家對象旁邊
  2. 從播放器讀取輸入檢查,如果他/她按下或釋放 按鈕搶對象
  3. 變化的位置遊戲對象將在 角色
  4. 中製作抓取的GameObject子項。所以兩者一起移動

該腳本解決了上述所有步驟。您需要注意添加剛體和對撞機。您還需要將要收集的對象標記爲「項目」

附加說明:如果您將收集的項目設置爲另一個具有網格的GameObject的子項(例如手形),則子項將更改其形狀。相反,使用放置在手的位置的空GameObject。並在檢查器中將Empty GameObject作爲此腳本的參數傳遞。

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class moveObject : MonoBehaviour { 

    public GameObject handEmptyGameObject; 
    GameObject item = null; 

    bool objectOnRange = false; 

    // Use this for initialization 
    void Start() { 
     //This is useful if you have just one item to collect in your scene 
     //if you have more than one, better remove it 
     item = GameObject.FindGameObjectsWithTag("item"); 
    } 

    // Update is called once per frame 
    void Update() { 
     if(Input.GetKeyDown(KeyCode.G) && objectOnRange) 
     { 
      print("Grabbing an object"); 
      item.transform.position = hand.transform.position; 

      item.transform.SetParent(hand.transform,true); 
     } 
    } 

    //You need to tag the GameObjec tto grab as "item" and set a 
    //collider and rigid bodies in the GameObjects 
    //This is to estimate if the player is close enough to the Object 

    void OnTriggerEnter(Collider other) 
    { 
     if(other.tag == "item") 
     { 
      objectOnRange = true; 
      item = other.gameObject; 
     } 
    } 

    void OnTriggerExit(Collider other) 
    { 
     if(other.tag == "item") 
     { 
      objectOnRange = false; 
      item = other.gameObject; 
     } 
    } 

}