JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Playing with changing angles smoothly</h2>
<input id="startButton" type="button" value="Start" onclick="start();" />
<input id="stopButton" type="button" value="Stop" onclick="stop();" />
<div id="letterhome"></div>
</div>
JavaScript
/**
* Main function
*/
function AnimatedLetter(text) {
// ----------------------------- Private variables -------------------------------
var letter = document.createElement("span"),
textNode = letter.appendChild(document.createTextNode(text)),
//direction = rand(-Math.PI,Math.PI), //This is angle in radians
direction = 0, //This is angle in radians
dir_change = 0, // This says how much is direction changing at the moment
speed = 5, // Speed of the element
speed_change = 0.2, // Speed change
radius = 50, // Max raduis from origin - not used
origPos = null, // Is necessary to make a difference between absolute window position
// and elements positionoriginating at alements home location
// In other words, this is used because we're using relative position here
currentPosition = null, // Will be an array of 2 numbers, representing[x,y]
targetPosition = [300,300], //Fly to position
nextDecleration =50 ;
// ------------------------------ Private methods --------------------------------
/**
* This method does all the calculations that we need in order to move our text
*/
function fly() {
var angle_to_target, // Why is this not global?
dx,dy,
distance,
dPhi = Math.PI / 50; // delta phi, for the angle difference
// Looking at target, and going towards it.
if(targetPosition!==null) { // redundant check?
angle_to_target = angle_between_points(currentPosition, targetPosition);
// Next 2 if statements are to avoid funny behaviour, since going from `direction = 179`
// to `angle_to_target=181` , will return instead of 2 degrees, -358 (that's the way
// atan2 works :) ). So, we simply add 2*PI, and problem solved (Gotta love...