March 01, 2016

How to move object following sine curve in Unity?

Today I solved little task of moving objects following given direction. In my case it was sine curve.

Scene setup.

There are minimal set of objects on scene: camera, light, cube and sphere. Camera rotated by 90 degrees around X axis and lifted up by Y axis, so we're watching scene vertically. Cube has Rigidbody attached; property Use Gravity is disabled on it. Sphere has just a regular SphereCollider.

Mathematical background.

We want to move
Cube to Sphere adding sinusoidal vibration perpendicularly to the moving direction. At the beginning we need to calculate vector of moving direction and orthogonal vector for it. We will multiple orthogonal vector by result of sinus function (time is an argument).


Attach script Mover to Cube object. In the Start() method we will save both vectors and start time. Finally, the main magic is here in single line of code of FixedUpdate() method. We need calculate magnitude of orthogonal vector using classical formula of periodical vibration: y = a * sin(w*x), where a - is amplitude of vibration, w - is frequency of vibration, x - is time in our case. After that we will perform addition of two vectors and assign to Rigidbody.

That's all! You can download all sources from Github.