Oscillation animation

I want to create an oscillation effect of an object. I use the following code:

hypeDocument.customOscillationMotion = function(element, amplitude, frequency, phase) {
  // Get the current time in milliseconds
  var currentTime = new Date().getTime();

  // Calculate the vertical displacement based on the amplitude, frequency, and phase
  var displacement = amplitude * Math.sin((2 * Math.PI * frequency * currentTime / 1000) + phase);

  // Apply the displacement to the element's position
  var newY = element.originalTop() + displacement;
  element.setTop(newY);
};

// Set the parameters for the oscillation motion
var elementId = 'yourCycleElementId';
var amplitude = 10;
var frequency = 1;
var phase = 0;

// Get the element by its ID
var cycleElement = hypeDocument.getElementById(elementId);

// Start the oscillation motion
hypeDocument.customOscillationMotion(cycleElement, amplitude, frequency, phase);

However I cannot make this work. Any help?
Thank you in advance.

There's a few things wrong/that you'll need to change.

I assume you are running this code during an On Scene Load event. In this case, you will still need some sort of timer to drive the animation running repeatedly. The better way to do this is probably to use requestAnimationFrame() but for simplicity you could just setup a repeating timer:

window.setInterval(function () {
	hypeDocument.customOscillationMotion(cycleElement, amplitude, frequency, phase);
}, 17);

17 is the number of milliseconds to use for 60fps.

Problem number 2 is that elements don't have an originalTop() value. You'll want to store the original top outside of the oscillation function, and then fetch it inside. I will use the Hype API to do so.

storing:

	var originalTop = hypeDocument.getElementProperty(cycleElement, 'top');
	cycleElement.setAttribute("data-originalTop", originalTop);

retrieving:

    var originalTop = parseFloat(element.getAttribute("data-originalTop"));

Problem number three is there's no setTop() property of elements. While there are native HTML ways, if you're using a Hype element it is better to use the Hype API again:

	  hypeDocument.setElementProperty(element, 'top', newY);

Then you'll find this works as you expect. Here's the sample document I made to test:

oscillation.hype.zip (15.4 KB)

One small note that might also help is that Hype has a special Math Equation timing function that lets you enter in JavaScript for items like this. Please see posts like:

https://forums.tumult.com/t/math-equation-in-easing-functions-how-to/11496/5

3 Likes

Jonathan this was very helpful!! Works like a charm!!

1 Like