Game Object Zigzag Movement from Top to bottom in Unity

I have seen in Unity forums that few people are struggling to get the zigzag movement of the game objects in unity. Using the following C# script you can achieve your Game object’s zigzag movement from top to bottom in unity. So, just attach this script to your game object and get the zigzag movement.

C# Script for Game Object Zigzag Movement in Unity

public class ObjectController : MonoBehaviour

    public float frequency = 10.0f; // Speed of sine movement
    public float magnitude = 1.0f; //  Size of sine movement, its the amplitude of the side curve
    public float speed = 1.0f;

    Vector3 pos;
    Vector3 axis;

    // Start is called before the first frame update
    void Start()
        // intialization for zigzag parameters
        pos = transform.position;
        axis = transform.right;

    // Update is called once per frame
    void Update()
        pos += Vector3.down * Time.deltaTime * speed;
        transform.position = pos + axis * Mathf.Sin(Time.time * frequency) * magnitude; // y = A sin(B(x)) , here A is Amplitude, and axis * magnitude is acting as amplitude. Amplitude means the depth of the sin curve


This code uses the mathematical Sin curve formula to calculate the position of the game object on each frame update.

As you can see in the above code, by changing the values of frequency, magnitude and speed, you can make variations in the movement. Frequency determines how fast the zigzag movement will occur. magnitude decides how much will be the depth of the sin curve. And similarly, speed variable controls the top to the bottom speed of the object.

That’s it. This is you can get Game Object Zigzag Movement in Unity.

Here you can find many other helpingĀ Tutorials & Code Snippets.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: