- Home /
How to move prefabs array in sine wave?
I'm rather new to C# and Unity, so appologize if the question is too basic.
I have an array of prefabs instantiated and I'd like to move them like a sine wave. Attached it's how it looks so far (they've only been created).

I reckon each prefab would need to be in a different position of the wave, so maybe there'd be a delay of their values?
Any help would be appreciated. Thanks
 using UnityEngine;
 using System.Collections;
 
 public class SineWave : MonoBehaviour {
 
     public int numberOfDots = 28;
     public GameObject[] waveDots;
     public GameObject waveDotPrefab;
 
     private object sineWave;
 
     void Start()
     {
         // re-initilaze array to get correct size
         waveDots = new GameObject[numberOfDots];
 
         // instantiate all prefab clones
         for (int i = 1; i < numberOfDots; i++)
         {
             waveDots[i] = Instantiate(waveDotPrefab, new Vector3(0, 0, i), Quaternion.identity) as GameObject;
         }
     }
 
     void Update()
     {
         // move the prefab clones as a sine wave
         for (int i = 1; i < numberOfDots; i++)
         {
             // this was just part of my tries and fails
             //waveDots[i].transform.position = new Vector3(0, 0, 0);
         }
 
     }
 
 }
Answer by Hellium · Nov 04, 2016 at 08:26 PM
Try this :
   Vector3 position = waveDots[i].transform.position ;
   position.x = Mathf.Sin(Time.time + i *factor) * amplitude ;
   waveDots[i].transform.position = position ;
Where factor is a floating value you will have to choose to make your sine wave smooth or not. A small value will make the wave smoother but with a low "frequency".
Thanks! But that makes the spheres move in the x axis only. I'm having issues in moving them like that ugly black wave I've drawn. They're already instantiated in a row in the z axis, so that should be enough to move them in the x axis, I'd guess.. =/

Answer by frederik99 · Nov 04, 2016 at 09:44 PM
like this?
 //scales the wave vertically
 public float amplitude;
 //scales the wave horizontally 
 public float waveLength;
 //shifts the wave
 public float phase;
 
 void Update() {
         
     for (int i = 1; i < numberOfDots; i++) {
 
         float normalizedProgress = (float)i / (numberOfDots - 1);
         float x = normalizedProgress * waveLength + phase;
         Vector3 position = (Vector3.forward * i) + Vector3.up * Mathf.Sin(x) * amplitude;
     }
 }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                