**"Coding Druid"** series is my **horizontal programming** practice notes, each part around a topic like mathematical, physics, electronic, graphics, sound, etc., implemented in several programming languages.

**Coding Druid**

Part: Math

Chapter: Trigonometric Function

Section: Unity3D

*In other sections, I visualized Trigonometric function (Sine and unit circle) by MaxMSP, Python, JavaScript(React):*

This time I use **Unity3D** to implement it.

In the Python version, the data visualization Library Matplotlib was used. With Unity I just draw it according to the trigonometric function algorithm.

Firstly, Let a point move with the Sine function curve.

Put a Sphere in the scene, and let its `position.x`

increase at a constant speed, then `position.y = sin(position.x)`

.

Vector3 posSine = sphere.localPosition;

posSine.x += speed;

posSine.y = Mathf.Sin(posSine.x);

sphere.localPosition = posSine;

Next, draw a path of the sphere moving along the unit circle.

Note that here, set the radius of the unit circle to 1, and set the period length of Sine to 2Pi. That is as shown in the previous sections, the unit circle shares a coordinate system with Sine.

Formula to drawing a circle:

x = cos(t);

y = sin(t);

The param `t`

here, in fact is the `position.x`

of the Sine in previous step.

Then move the center of the circle to the left, to make the rotating starting point of the unit circle consistent with the starting point of Sine.

Vector3 posCircle = posSine;

posCircle.x = Mathf.Cos(posSine.x) - 1f;

posCircle.y = Mathf.Sin(posSine.x);

circleDot.localPosition = posCircle;

Combine the Sine and unit circle:

In the previous articles, I drew the path of the curve to make it more clearly, such as Python:

I plan to be lazy with Unity.

Add the `Trail Renderer`

directly to the two spheres, and let them draw path trail effect themselves.

Well, The default trail is a bit strong...

OK let's change it. After searching `trail`

in the Unity Assets Store I find a free good track effect：

After installation the asset there are a lot of effects. Then pick a material by liking:

Attach the material to the Trail Renderer.

**Final Effect**:

*In the released source code, I added Trail Renderer to an empty GameObject and moved with the sphere. I didn't add the track directly to the sphere. There is no special reason, just practice of Unity newbie.*

Reference article: Building a Graph Visualizing Math

**Talk is cheap. Show me the code!**

This demo of the "Coding Druid" series is open source here:

https://github.com/avantcontra/coding-druid

You can find more resources in my site floatbug.com.

Or you may **buy me a coffee** in my Patreon. Your encouragement is my driving energy!

Cheers~

Contra

- Website: floatbug.com
- Github: avantcontra
- Facebook: avantcontra
- Twitter: avantcontra
- Instagram：avantcontra
- Patreon (
**buy me a coffee**XD): avantcontra

## Discussion (0)