Randomly Play Animator's Animation
Randomly Play Animator's Animation
I am working on platform based game on Unity game engine so various obstacles contain movement and I created animation for this purpose.
I have created moving animation of obstacle from left to right and right to left side and it was working properly. It get started from 0 unit and completed at 10 units and traveling back to 0 unity place always.
In this I want to add variation, its starting point will be dynamic so one time it get spawned on 5 unit and complete rest journey of pre recorded animation, next time it spawn at 3 unit and complete rest journey up to 10 units. and then travel back.
So that game player can't predict the behaviour of obstacles otherwise its easy to predict obstacle movement. I hope you are getting me into this so provide me some suggestion.
2 Answers
2
You can use the random.range function to return a random number between (min, max)int startingPoint = Random.Range(0, 10) this will return a random integer with between 0 and 11, as the 10 is inclusive that will be the highest possible number.
int startingPoint = Random.Range(0, 10)
If you're using an animation component you can then skip to that point in the animation clip using myAnimator.playbackTime = startingPoint
myAnimator.playbackTime = startingPoint
Official unity doc on random.range
that is what the
myAnimator.playbackTime = startingPoint part is for. myAnimator will be the component your animation is on. playbackTime is the playback position in the animations timeline. say for example startingPoint is 2, myAnimator.playbackTime = startingPoint will start your animation at 2 seconds into the animation. this is what you want correct? docs.unity3d.com/ScriptReference/Animator-playbackTime.html– remy_rm
Aug 23 at 12:29
myAnimator.playbackTime = startingPoint
myAnimator.playbackTime = startingPoint
In this case it would be better to decouple your visuals animation and the randomization logic.
Make your obstacles reuse a common animation which doesn't change the position of the object (Like just sprite animation).
And then control the positioning using another script that randomly selects a distance to move.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Basically my question was about playing animation from random point - not just on moving animation but any kind of animation I want to start at random point from recorded click - I completely knew about random class and its working so my focus was on animation rather than random class.
– Siddharth
Aug 23 at 10:47