Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question What is the most efficient way to procedurally launch an object?

Discussion in 'Scripting' started by SteveSopoci, Aug 5, 2020.

  1. SteveSopoci

    SteveSopoci

    Joined:
    Jul 23, 2020
    Posts:
    1
    Hi,

    I hope that everyone is well!

    As the title suggests, I am just curious to see if anyone has any boilerplate code to procedurally launch an object in random directions while keep performance in mind.

    Cheers!
     
    Last edited: Jan 7, 2023
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,888
    How about this? Raycasting seems... overkill.

    Code (CSharp):
    1. int x = /* player spawn x grid coordinate */
    2. int y = /* player spawn y grid coordinate */
    3. List<Vector2> possibleDirections = new List<Vector2>();
    4.  
    5. // Can we go left?
    6. if (x > 0) {
    7.   possibleDirections.Add(new Vector2(-1, 0));
    8. }
    9. // Can we go up and left?
    10. if (x > 0 && y > 0) {
    11.   possibleDirections.Add(new Vector2(-1, -1));
    12. }
    13. // Can we go up?
    14. if (y > 0) {
    15.   possibleDirections.Add(new Vector2(0, -1));
    16. }
    17. // Can we go up and right?
    18. if (x < GridLength - 1 && y > 0) {
    19.   possibleDirections.Add(new Vector2(1, -1));
    20. }
    21. // Can we go right?
    22. if (x < GridLength - 1) {
    23.   possibleDirections.Add(new Vector2(1, 0));
    24. }
    25.  
    26. // FILL IN THE REST OF THE DIRECTIONS...
    27.  
    28. Vector2 directionToLaunchPlayer = possibleDirections[UnityEngine.Random.Range(0, possibleDirections.Count)];
     
    Yanne065 likes this.