jeudi 15 août 2019

Dotted line bouncing on Unity

I am trying to replicate a shooter from any bubble shooter. Dotted line that the bubble will follow.

What I am trying to do is, create a dotted line that bounces (reflects) when getting close the camera limits. Also, to stop creating more dots when Hit with a Bubble.

The line so far bounces, but not correctly (see corners). Also, it does not stop when hit with a Bubble (blue dot).

private void DrawPoints() {
        bool hasReversed = false;
        bool reversedLeft = false;

        var leftEdge = mainCamera.ScreenToWorldPoint(new Vector3(0, 0, 0));
        var rightEdge = mainCamera.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0));
        var normalDir = shootDir.normalized;

        int count = 0;

        for (var i = 0; i < dots.Count; i++) {
            var dot = dots[i];
            dot.GetComponent<SpriteRenderer>().color = color;

            var newPos = new Vector2(normalDir.x, normalDir.y) * i * DotGap;
            if (hasReversed) {
                newPos.x += reversedLeft ? (-rightEdge.x + Constants.BubbleRadius/2) * 2 * count : (rightEdge.x - Constants.BubbleRadius/2) * 2 * count;
                //newPos.x += reversedLeft ? (-rightEdge.x + Constants.BubbleRadius) * 2 : (rightEdge.x - Constants.BubbleRadius) * 2;
            }

            //newPos += normalDir * delta;

            dot.transform.localPosition = newPos;

            RaycastHit2D hit = Physics2D.Raycast(newPos, shootDir);
            if (hit.collider != null) {
                float distance = Vector2.Distance(hit.transform.position, newPos);
                if (distance < Constants.WhiteCircleRadius + Constants.BubbleRadius) {
                    dot.SetActive(false);
                    Debug.Log("Found!: " + distance + " " + hit.collider.name);
                    break;
                } else {
                    dot.SetActive(true);
                }
            }

            if (dot.transform.localPosition.x <= leftEdge.x + Constants.BubbleRadius) {
                hasReversed = true;
                reversedLeft = true;
                normalDir = Vector2.Reflect(normalDir, Vector2.left);
                count++;
            }
            else if (dot.transform.localPosition.x >= rightEdge.x - Constants.BubbleRadius) {
                hasReversed = true;
                reversedLeft = false;
                normalDir = Vector2.Reflect(normalDir, Vector2.right);
                count++;
            }
        }
    }

The image as follows: The red dot is the pivot (start of the dotted line). The blue dot, is a bubble.





Aucun commentaire:

Enregistrer un commentaire