Home > Software engineering >  How can I animate twitching movement with code?
How can I animate twitching movement with code?

Time:06-03

I created an animation to illustrate what I'd like to achieve with code: Example of twitches

It stays still and occasionally rotates quickly, then returns to its original state.

Would be great to be able to turn it up upon hovering for example, to make it shake violently for 1 sec. But that's less important.

CodePudding user response:

Building upon Marquizzo's answer:

Just use Math.random() to update the rotation on each frame.

Using Math.random() on its own, won't achieve this effect. If you want it to stay around one place, like shown in your GIF, you can do it like so:

function getRandomDecimal(min, max) {  //Generates the rotation value
    var rand = Math.random()*(max-min)   min;
    var power = Math.pow(10, 2);
    return Math.floor(rand*power) / power;
}

function render(){
    renderer.render(scene, camera);
    requestAnimationFrame(render);

    objectToTwitch.rotation.set(getRandomDecimal(-1, 1)); //Set the rotation to a random decimal from `-1` to `1`.
};

render(); //Calling the function manually the first time

Let me explain this code. We start with a custom function called getRandomDecimal(), which takes the parameters of min and max. We then set the rotation of you object to a random number between -1, min, and 1, max. This changes 60 times a second, or the user's browser's frame rate. If this "twitch" effect happens too fast, you can fire the line of code somewhere else in your program.

That should do it~

  • Related