Search Unity

Instantiate objects on a path

Discussion in 'Scripting' started by Arashikage, Feb 14, 2014.

  1. Arashikage

    Arashikage

    Joined:
    Dec 8, 2013
    Posts:
    14
    I'm working on a game where you draw a line and blocks get instantiated with a rotation so they follow the angle of the line to create a reasonably smooth path.
    Here's my code:

    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var blockPrefab : Transform;
    5. var lastPosition : Vector3;
    6.  
    7.  
    8. function Update()
    9. {
    10.     if (Input.GetMouseButton(0))
    11.     {
    12.         var mouseRay : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    13.         var newPosition : Vector3 = mouseRay.origin - mouseRay.direction / mouseRay.direction.z * mouseRay.origin.z;
    14.         if (newPosition != lastPosition)
    15.         {
    16.             GenerateBlocks(newPosition);
    17.         }
    18.     }
    19. }
    20.  
    21. function GenerateBlocks (newPosition : Vector3)
    22. {
    23.     var dX : float = lastPosition.x - newPosition.x;
    24.     var dY : float = lastPosition.y - newPosition.y;
    25.     var rad : float = Mathf.Atan(dY/dX);
    26.     var degr : float = rad * Mathf.Rad2Deg;
    27.  
    28.     Instantiate(blockPrefab, newPosition, Quaternion.Euler(dX,dY,degr));
    29.  
    30.     lastPosition = newPosition;
    31. }
    32.  
    It's based on the answer found here: http://answers.unity3d.com/questions/285040/draw-a-line-in-game.html and it works fairly well but there are two problems I'm hoping someone can help me with.

    1) Every 10th block (give or take) gets instantiated at about 45 degrees to the adjacent blocks which essentially creates a road block in the path (not what I want). How can I set a limit so that each new block can only be rotated within a certain number of degrees of the previous block? Or maybe just smooth out the angles somehow?

    2) If I draw a line slowly, lots of blocks get instantiated in a small area. If I draw the line quickly, they can be spaced out so far that there's a gap between them. How can I even out the spacing so that they're instantiated the same distance apart regardless of the speed at which the line is drawn? I know the problem has something to do with the fact that I'm using Update, but I don't know how to fix it.

    I'm a programming n00b so any help would be greatly appreciated.