- Home /
Random Entry of Object
At present I am developing Bird Hunting game in 2D. For which I want to create animation like bird come into screen from random position. I know about creating animation at design time but at present I want to create run time animation.
So how to achieve this? Small suggestion become enough for me.
Do you mean a smooth transition of bird's position from point A to point B ?
Yes, you understand this right but both position is random for bird. There is no rigid body attached to game object.
Answer by aeroson · Jan 17, 2014 at 02:22 PM
The fastes way to do this, is to instantiate bird at random position and set his endPosition.
GameObject instantiatedBird=GameObject.Instantiate(birdPrefab,Random.insideUnitSphere,Quaternion.identity);
instantiatedBird.GetComponent<BirdLogic>().endPosition=Random.insideUnitSphere;
Then in BirdLogic you would do this
public Vector3 endPosition; // bird's target position
Vector3 startPosition;
float time=0; //
void Start() {
startPosition = transform.position; // remember start position
}
void Update() {
time+=Time.deltaTime;
time=Mathf.Clamp01(time); // make sure time is between 0 and 1
transform.position = Vector3.Lerp(startPosition, endPosition, time);
}
If you wish to set the bird's rotation according to the direction he moves, add this to the Update function:
transform.rotation = Quaternion.LookRotation(endPosition-transform.position);
Thanks for you great help. If I want to choose location from outside the camera visible region then how to get that location.
http://answers.unity3d.com/questions/405707/spawn-outside-camera-view.html
Camera.ViewportToWorldPoint (x=0 is left, x=1 is right, y=0 is bottom, y=1 is top)
Random.value returns random number from 0 to 1.
This will make start pos left of camera from 0.5 to 1.5 times the width of camera. Note the width of camera depends on how far from camera the point is, change to 10.0f to adjust that.
Vector3 startPos = Camera.main.ViewportToWorldPoint(new Vector3(-0.5f-Random.value,Random.value,10.0f));
$$anonymous$$ake end pos within camera view, that is from 0,0 to 1,1
Vector3 endPos = Camera.main.ViewportToWorldPoint(new Vector3(Random.value,Random.value,10.0f));
Thank you so much for you help and now I mark your answer as correct because it already work for me.
Your answer
Follow this Question
Related Questions
Single Time Animation Play 1 Answer
Crushy Bird Game Doubt 1 Answer
Detect animation completion in iTween 2 Answers
Move Object Using iTween 2 Answers
2D game animation is running 1 Answer