Cmaxster
Cmaxster

Reputation: 1195

Animating along a curve using Javascript & simple math

I feel like the solution is very simple, but in all honestly I failed math multiple times in high school, so I'm barely grasping even the basic concepts right now.

The idea is very simple.. I want to have a bunch of graphical objects tween animate from one side of a 300x300px div to the other side along randomized curved paths as if they were being tossed or dropped from the top left to the bottom right (and vice versa, back and forth).

I know I need to use some form of Trigonometry to solve this (sin, cos, tan??). I also already know how to get my two points (randomizing Y points, and then randomly putting x points on the positive or negative side of the 300px width). But the part where I have to actually calculate steps along a curve is beyond me.

Here's a crappy diagram of basically what I'm attempting.. I searched Google but all of the examples were way overcomplicated or too abstract. I just want to learn how to make a curve between two points.. That's it!

crappy diagram of what I'm attempting

So simple question: How do I randomize a curved animation (or plot points along a curve) between two points using vanilla JavaScript (no JQuery please).

Upvotes: 0

Views: 1709

Answers (2)

Rabindranath Andujar
Rabindranath Andujar

Reputation: 61

Actually, you only need very simple trigonometry (sine and cosine). If you are tossing something from a point (X0, Y0), the equations of motion are more like a parabolic trajectory.

From Wikipedia:

Displacement and coordinates of parabolic throwing

At any time t, the projectile's horizontal and vertical displacement are:

x = X0 + v0 * t * cos(theta)
y = Y0 + v0 * t * sin(theta) − 0.5 * g * t * t

So there you go, your coordinates in pixels for every t time step. You may define theta and v0 as constants or also as random values to make the animation more chaotic and lively. Play with the value of g (in Earth it is 9.8 m/s²), because probably when scaling to pixels/s² it might overshoot. Also you may want to give negative values to X0 and Y0 in order to intercept the descending part of the trajectories, leaving the ascending out of the div.

Upvotes: 1

SkizerCarz
SkizerCarz

Reputation: 13

First of all, if you would like a quick look into the math of JavaScript animations , you might consider visiting this link

Upvotes: 1

Related Questions