2017-08-14 103 views
0

因此,我正在開發一款手機遊戲,其中我已觸摸來自資產商店的資產的輸入。除了一件事之外,這一切都很完美:我想實現「拖放」功能,所以當我拿起一個物品時,它應該跟隨我的手指位置。但是因爲操場是一個球體,所以我必須用Raycast進行運動。所以我的計劃是該項目應該遵循Raycasts的立場。我現在的嘗試是這樣的:Unity Raycast Movement

public void DragTo(float screenX, float screenY) 
{ 
    if (draggingObject == null) 
    { 
     return; 
    } 

    Debug.Log("Dragging"); 

    //Converts the screen space to world space 
    Vector3 mousePosFar = new Vector3(screenX, screenY,  Camera.main.farClipPlane); 
    Vector3 mousePosNear = new Vector3(screenX, screenY, Camera.main.nearClipPlane); 

    Vector3 mousePosF = mainCam.ScreenToWorldPoint(mousePosFar); 
    Vector3 mousePosN = mainCam.ScreenToWorldPoint(mousePosNear); 

    //shoots an ray to the world space 
    RaycastHit hit; 

    if (Physics.Raycast(mousePosN, mousePosF - mousePosN, out hit)) 
    { 
     float step = speed * Time.deltaTime; 
     draggingObject.GetComponent<Rigidbody>().MovePosition(hit.point); 
    } 
} 

我已經嘗試了以下選項:

draggingObject.GetComponent<Rigidbody>().MovePosition(hit.point); 
draggingObject.transform.position = hit.point; 
draggingObject.transform.position = normal; 

他們所有的工作,但他們都有真正的越野車和怪異的行爲。另外當我不凍結z。剛體上的物體剛剛在z軸上「飛」,直到到達相機。然後再傳送下來,一切都重新開始。所以它在射線上飛起來。所以,如果你有任何想法,爲什麼發生這種情況讓我知道。任何幫助表示讚賞。 (另外不要忘記,它的一切都發生在球體上)

更新: 它現在的作品。當拖動開始時,我將圖層從對象改爲「忽略Raycast」,並在結束時將其更改回「默認」。

回答

0

現在工作!當拖動開始時,我將圖層從對象改爲「忽略Raycast」,並在結束時將其更改回「默認」。