RayCastHit2D导致不一致的碰撞

时间:2017-06-22 15:40:00

标签: unity3d unity5

我正在制作一款2.5D自上而下的游戏。我创建了一个脚本,用于在我的网格上放置对象。但它表现得非常奇怪。它按照应该的方式捕捉到网格,但是如果我尝试将对象放置在网格上位于游戏中对象的顶部或左侧,则会触发碰撞(请参阅GIF):

enter image description here

我正在使用if ([System.Boolean](Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue)) { #windows } else { #Not windows } 来检测碰撞,这是我的脚本:

RayCastHit2D

为了让我的GameObjects捕捉到Grid,我必须将Pivots设置为右下角(如果它们是中心,它们将被放置在Grid交叉点)。 这意味着我必须像这样定制他们的对撞机:

enter image description here

正如你所看到的,我的Collider正是一个网格(我使用16ppu):

enter image description here

我在这里难过,有没有人知道这里有什么问题?可能值得添加,我尝试将它们的碰撞器更改为0.9而不是1,但那只是完全禁用 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 } } } } } ,我可以将对象放在彼此之上等。

1 个答案:

答案 0 :(得分:0)

可能是由于你的对齐修正,你的光线投射是从瓷砖角而不是中心发射,这会产生模棱两可的结果。您可以通过查看是否向光线投射开始位置添加半个图块的偏移量来修复此问题(不确定是否为+或 - )来测试这一点:

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

如果这个答案不正确,请随意关注。它基于预感,我不会在这台机器上统一试用。

相关问题