2016-12-06 85 views
1

使用此代碼,我可以在「玩家」擊中對象時顯示對象的標籤,但是如何讓標籤在碰撞之前出現?我的意思是,例如,當玩家站在物體前方3米處時?在碰撞前顯示對象標籤

private bool showInfo = false; 

void OnCollisionEnter(Collision col) 
{ 

    if (col.gameObject.tag == "Player") 
    { 
     showInfo = true; 
    } 

} 

void OnCollisionExit(Collision collisionInfo) 
{ 

    if (collisionInfo.gameObject.tag == "Player") 
    { 
     showInfo = false; 
    } 
    } 

void OnGUI() 
{ 

    if (showInfo) 
    { 
     GUIStyle myStyle = new GUIStyle(); 

     Font myFont = (Font)Resources.Load("Fonts/comic", typeof(Font)); 
     myStyle.font = myFont; 

     myStyle.fontSize = 24; 

     myStyle.normal.textColor = Color.red; 

     GUI.Label(new Rect(10, 10, 100, 20), gameObject.tag, myStyle); 
    } 

} 

回答

2

創建啓用了觸發選項aditional的對撞機,並使其比對撞機(您要檢測預碰撞大小),並調用OnTriggerEnter作用更大。

void OnTriggerEnter(Collision col) 
{ 

    if (col.gameObject.tag == "Player") 
    { 
     showInfo = true; 
    } 

} 

或者..你可以在對象的更新檢查玩家的距離與Vector3.distance(Vector3 obj1, Vector3 obj2),如果它小於3米設置showInfotrue

+1

thx,它幫助了很多:) – artur47wien

1

Driconmax的解決方案是我的方式做它。

但是,爲了提供另一種解決方案,您可以在移動方向上創建一個3米長的光線投射,並且如果它註冊了一個命中,則顯示該對象信息。但我認爲這是在大多數情況下的子解決方案