modified animation function. It is still not working the way I want it to work (i dont really want to use global variables, but at the moment its working)