2017-04-22 78 views
1

我想沿着另一個gameobject的輪廓移動一個gameObject的實例。它是一個統一的2D項目。Raycast2D實例化對象命中並旋轉實例

我當前的代碼:

Vector3 mousePosition = m_camera.ScreenToWorldPoint(Input.mousePosition); 
    RaycastHit2D hit = Physics2D.Raycast(new Vector2(mousePosition.x, mousePosition.y), new Vector2(player.transform.position.x, player.transform.position.y)); 
    if (hit.collider != null && hit.collider.gameObject.tag == "Player") { 
     if (!pointerInstance) { 
      pointerInstance = Instantiate(ghostPointer, new Vector3(hit.point.x, hit.point.y, -1.1f), Quaternion.identity); 
     } else if(pointerInstance) { 
      pointerInstance.gameObject.transform.position = new Vector3(hit.point.x, hit.point.y, -1.1f); 
      pointerInstance.gameObject.transform.eulerAngles = new Vector3(0f, 0f, hit.normal.x); 
     } 

    } 

不幸的是,遊戲對象不會對鼠標的playerObject左側的位置旋轉有時也被關閉。我試圖用Quaternion.LookRotation(hit.normal)使用Instantiate(),但也沒有運氣。

這裏是我想達到的草圖: instance of tree is shown on the surface of the player facing towards the mousepointer

任何幫助表示讚賞。謝謝!

回答

1

最好使用數學方法而不是物理方式(光線投射),因爲在光線投射中,您必須多次投射光線來檢查命中點並旋轉對象,這會使遊戲滯後。

安裝這個腳本到您的實例化對象:

using UnityEngine; 
using System.Collections; 

public class Example : MonoBehaviour 
{ 
    public Transform Player; 

    void Update() 
    { 
     //Rotating Around Circle(circular movement depend on mouse position) 
     Vector3 targetScreenPos = Camera.main.WorldToScreenPoint(Player.position); 
     targetScreenPos.z = 0;//filtering target axis 
     Vector3 targetToMouseDir = Input.mousePosition - targetScreenPos; 

     Vector3 targetToMe = transform.position - Player.position; 

     targetToMe.z = 0;//filtering targetToMe axis 

     Vector3 newTargetToMe = Vector3.RotateTowards(targetToMe, targetToMouseDir, /* max radians to turn this frame */ 2, 0); 

     transform.position = Player.position + /*distance from target center to stay at*/newTargetToMe.normalized; 


     //Look At Mouse position 
     var objectPos = Camera.main.WorldToScreenPoint(transform.position); 
     var dir = Input.mousePosition - objectPos; 
     transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg); 

    } 
} 

有用的解釋

ATAN2:

ATAN2(Y,X)爲您提供了與x軸之間的夾角和矢量(x,y),通常用弧度表示,並且對於正y你得到一個0和π之間的角度,對於負y,結果在-π和0之間。 https://math.stackexchange.com/questions/67026/how-to-use-atan2


返回其談是Y/X弧度的角度。返回值是x軸和從零開始並終止於(x,y)的2D向量之間的角度。 https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html

Mathf.Rad2Deg:

弧度到度的轉換常數(只讀)。

這等於360 /(PI * 2)。