#StackBounty: #c# #unity3d #2d #raycasting Instantiate predefined number of object along a raycast in Unity

Bounty: 100

I have a raycast that’s being rendered every frame based on 2 points, and those 2 points change position each frame.

What I need is a system that doesn’t need a direction, or a number of objects, but instead takes in 2 points, and then instantiates or destroys as many objects as necessary to get the instantiated objects from one side to another minus spaceBetweenPoints. If you wanted you could think of it as an Angry Birds Style slingshot HUD, except without gravity, and based on raycasts.

My Script:

    public int numOfPoints; // The number of points that are generated (This would need to chnage based one the distance in the end)
    public float spaceBetweenPoints; // The spacing between the generated points
    private GameObject[] predictionPoints; // The prefab to be gernerated
    private Vector2 firstPathStart; // The starting point for the raycast (Changes each frame)
    private Vector2 firstPathEnd; // The ending point for the raycast (Changes each frame)
    
    void start()
    {
         predictionPoints = new GameObject[numOfPoints];
         for (int i = 0; i < numOfPoints; i++)
         {
              predictionPoints[i] = Instantiate(predictionPointPrefab, firePoint.position, 
              Quaternion.identity);
         }
    }

    void Update
    {
         Debug.DrawLine(firstPathStart, firstPathEnd, UnityEngine.Color.black);
         DrawPredictionDisplay();
    }

    void DrawPredictionDisplay()
    {
         for (int i = 0; i < numOfPoints; i++)
        {
            predictionPoints[i].transform.position = predictionPointPosition(i * spaceBetweenPoints);
        }
    }

    Vector2 predictionPointPosition(float time)
    {
        Vector2 position = (Vector2)firstPathStart + direction.normalized * 10f * time;
        return position;
    }

The current system simply takes in a starting position, a direction, and then moves a preset number of objects in that direction based on time. This way of doing it also causes problems because it’s endess instead of only going till the end of the raycast: (Pardon my drawing skills)

Exampel Image

Blue line = raycast
Black dots = instantiated prefab
Orange dot = raycast orange
Green dot = end of raycast

Notes:

  • direction is the momentum which I set in the editor, I needed it to put together what I currently have working, but it shouldn’t be necessary when running based on points.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.