Today I changed the form of specifying a tween effect. It was originally specified as a string (e.g., “linear” or “vibrate_right”) but now it is defined as an object literal. The first member field of the object has to be effect
and its value specifies the effect to be used. If the effect requires additional parameters then those may also be provided within the object literal, but defaults are provided for all values so they aren’t strictly necessary.
Here is the code for the processEffect
function I described yesterday. As noted in the comments it’s kind of annoying to have to peel the effect description objects apart every time this routine is called, but that can be improved later by creating some external state variables. Whether you as a developer would want to pursue that course of action is a matter of taste. Do you want more speed or to use less memory?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
function processEffect(pStart,pEnd,alpha,omega,i,mMethod) { var result = 0.0; var keyList = Object.keys(mMethod); if (keyList[0] == "effect") { //for now this should always be the case var effect = mMethod.effect; if (effect == "linear") { result = pStart + (pEnd - pStart) * (i - alpha) / (omega - alpha); //returning result in each branch allows for possible type flexibility return result; } else if (effect == "vibrate_right") { //retrieve required/expected additional parameters //yes, it's annoying that we have to peel this apart every time... // ...but we can think of adding improvements later var frequency = 1.0; var amplitude = 50.0; var decay = "linear"; for (var ii=1; ii<keyList.length; ii++) { if (keyList[ii] == "freq") { frequency = mMethod.freq; } else if (keyList[ii] == "amplitude") { amplitude = mMethod.amplitude; } else if (keyList[ii] == "decay") { decay = mMethod.decay; } } var multiplier = i - alpha - (Math.PI*0.5); multiplier *= frequency; multiplier = Math.cos(multiplier); multiplier *= amplitude; if (decay == "linear") { multiplier *= (omega-i) / (omega-alpha); } else { alert("We're not dealing with this for now, and we may never!") } //var multiplier = Math.cos(i - alpha - Math.PI*0.5)* 100 * (omega-i) / (omega-alpha); result = pStart + multiplier; return result; } } } |
Now that this is in place it can (theoretically) be used to modify a wide variety of tweens. The code for each type of modification need only be written once.
Here’s the animation with a new block showing that the vibrate effect works as intended. There are a lot more twists I could put on this thing but the basics are working for now.