Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Platform move left and right randomly

Discussion in '2D' started by Keiji1, Oct 22, 2021.

  1. Keiji1

    Keiji1

    Joined:
    Jul 8, 2021
    Posts:
    4
    Hi, I am pretty new to Unity and I am trying to make a platform jumping game. I got this script working as it should from a Youtube video but I wanted to make the platform move randomly because I have multiple platforms that gonna spawn when I start the game. So basically when the platform spawn 1 should go from left to right and the other should go from right to left.

    Code (CSharp):
    1.  
    2.     public Transform pos1, pos2;
    3.     public float speed;
    4.     public Transform startPos;
    5.  
    6.     Vector2 nextPos;
    7.  
    8.     // Start is called before the first frame update
    9.     void Start()
    10.     {
    11.         nextPos = startPos.position;
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.         if(transform.position == pos1.position)
    18.         {
    19.             nextPos = pos2.position;
    20.         }
    21.         if(transform.position == pos2.position)
    22.         {
    23.             nextPos = pos1.position;
    24.         }
    25.         transform.position = Vector2.MoveTowards(transform.position, nextPos, speed * Time.deltaTime);
    26.     }