I am using CreateJS to animate an object.
I want to move the circle
shape to a position that changes in a for loop.
var x = {
time: 200,
x: 0,
y: 0
};
I am going to change this variable after every time the shape animates in a for loop.
for(var i = 0; i < 4; i++) {
createjs.Tween.get(circle)
.to({x: hits.x, y: hits.y}, hits.time);
hits.x += 200;
hits.y += 200;
}
I have the increment value set to 4, but I am going to change it. This is why I am not directly using the .to
function every time I am animating it. I do not want to hardcode every loop for every single increment. I need to make a single function that can take in any increment value and animate it accordingly.
I tried this out, but then realized that the animation doesn't take place if another animation is in progress.
I then used an eval function to add all the values to a string, and then doing it as a whole, as the .to()
function is chainable.
var bounceString = "createjs.Tween.get(circle)";
for(var i = 0; i < 4; i ++) {
bounceString += ".to({x: hits.x, y: hits.y}, hits.time)";
hits.x += 200;
hits.y += 200;
}
bounceString += ";";
eval(bounceString);
By using the eval function with the string, I can use any increment value and animate the shape accordingly without having to hardcode it. However, there is a problem.
I have no clue why, but it says that the hits
variable is undefined. I also tried to define that variable in the bounceString
, but it did not work out. I also tried making it a global variable (as the whole code is in a function).
The error that shows up when I try to define hits
in bounceString
is this-
This happens only when I am trying to define the variable in the string itself.
I know that the eval
function is dangerous, but this is the only way. Is there any other way I can do this?