2017-06-22 143 views
0

我正在製作一款2.5D自上而下的遊戲。我創建了一個用於在我的網格上放置對象的腳本。但它的表現真的很奇怪。它捕捉到網格,因爲它應該,但如果我嘗試將對象放置在網格的頂部或左側,它會觸發一個碰撞(見GIF):RayCastHit2D導致不一致的匹配

enter image description here

我使用RayCastHit2D檢測collissions,這是我的腳本:

public GameObject finalObject; 

private Vector2 mousePos; 
private RaycastHit2D rayHitCollision; 
private RaycastHit2D rayHitInteractive; 
private Renderer rend; 
private Color green; 
private Color red; 

public LayerMask collisionLayer; 
public LayerMask interactiveLayer; 

void Start() 
{ 
    rend = GetComponent<Renderer>(); 
    red = Color.red; 
    red.a = .5f; 

    green = Color.green; 
    green.a = .5f; 

    rend.material.SetColor("_Color", green); 
} 

void Update() 
{ 
    //get pos of mouse 
    mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); 
    //place object at rounded mouse pos (snapping) 
    transform.position = new Vector2(Mathf.Round(mousePos.x), Mathf.Round(mousePos.y)); 

    if (GameManager.manager.mainState == GameManager.MainState.PLACEMENT) 
    { 
     //In order to collide with object, they must be on same layer, this includes tilemap stuff 

     rayHitCollision = Physics2D.Raycast(transform.position, Vector2.zero, Mathf.Infinity, collisionLayer); 

     //if tile is colliding with other tile show red, REMEMBER THIS IS EFFECTED BY LAYERS 
     if (rayHitCollision.collider != null) 
     { 
      rend.material.SetColor("_Color", red); 
     } 
     //if not colliding, check for mouse press and place 
     else 
     { 
      rend.material.SetColor("_Color", green); 
      if (Input.GetMouseButtonDown(0)) 
      { 
       if (rayHitCollision.collider == null) 
       { 
        //place object 
       } 
      } 
     } 
    } 
} 

爲了讓我GameObjects捕捉到網格,我不得不設置支點到右下角(如果他們是中心,他們被放置在Grid交叉點)。 這意味着我需要定製自己的對撞機,像這樣:

enter image description here

正如你可以看到我對撞機正好是一個網格(我用16ppu):

enter image description here

我在這裏難倒,有沒有人有任何線索這裏有什麼問題?可能值得添加,我試圖改變他們的碰撞體大小0.9而不是1,但是這只是完全禁用RaycastHit2D,我可以把對象放在彼此之上等。

回答

0

這可能是由於你的對齊修復你的光線投射從瓦片角落而不是中心發射,這會產生不明確的結果。如果要添加一個半瓦的光線投射的補償開始位置修復了這個你可以測試這一點通過看(不知道是+或 - ):

rayHitCollision = Physics2D.Raycast(transform.position + new Vector2(0.5f, 0.5f), Vector2.zero, Mathf.Infinity, collisionLayer); 

隨意downvote如果這個答案是不正確。這是基於預感,我沒有統一在這臺機器上試用它。

+0

爲什麼我會downvote有人試圖幫助我:)這聽起來像一個很好的(ish)的想法,我會盡快嘗試它,只要我回家! –

+0

您的預感似乎是正確的,我將它改爲'rayHitCollision = Physics2D.Raycast(transform.position + new Vector3(0.5f,-0.5f,0),Vector2.zero,Mathf.Infinity,collisionLayer); '現在唯一觸發碰撞的格子是左上角。看起來很奇怪,我不得不改變樞軸和這樣的事情,只是爲了讓它對齊網格。爲什麼不將樞紐中心對齊網格......看起來很愚蠢 –

相關問題