Search code examples
titaniumappcelerator

How to create shaking randomly images


I wanted to make a shaking image in a imageView in Appcelerator TItanium

What I would like to do is to randomly change the top position and the left position of an imageView, to do like a shaking image.

OriginalImageLeft = image.left;
OriginalImageTop = image.top;

if (Math.random() > 0.5){
    value = -1;
} else {
    value = 1;
} 

var viewAnimate = Ti.UI.createAnimation({
    duration: 2000,
    repeat:100,
    left: OriginalImageLeft + (Math.random() * 20 * value),
    top: OriginalImageTop + (Math.random() * 20 * value),
});

image.animate(viewAnimate)

But the code is not working, it calculates only one time the MathRandom() function so the shaking is not working.

Any idea ?


Solution

  • Create a function to calculate the position + doing the animation once. Then use the animation complete event to call that function again so it will calculate a new position + running the animation again. If you want to stop it just don't call the fuction again (e.g. add a counter/if-case around the function call).

    A short info why your code won't work:
    the OriginalImageLeft + (Math.random() * 20 * value) part is send to the native path once. So it will execute the Math.random() part in JS and send that number to the native App. The actual repeat part is executed with that calculated number.