2016-12-06 82 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米长的光线投射,并且如果它注册了一个命中,则显示该对象信息。但我认为这是在大多数情况下的子解决方案