- Home /
Move object up and down while moving forward
I have a bird model with an animation of its wings flapping. It's an "in place" animation. I'm trying to make the bird fly forward while moving up and down a little bit. I can get it to move forward and up, but it won't go down. It seems to get stuck in between the rise and fall functions and just flies straight. Here's my code:
using UnityEngine;
using System.Collections;
public class bird_fly : MonoBehaviour {
void Update () {
Go();
}
void Go(){
Vector3 newPosition = transform.position;
newPosition.z += 1 * Time.deltaTime;
transform.position = newPosition;
Rise();
}
void Rise(){
Vector3 newPosition = transform.position;
newPosition.y += 1 * Time.deltaTime;
transform.position = newPosition;
if (newPosition.y > 3) {
Fall();
}
}
void Fall(){
Vector3 newPosition = transform.position;
newPosition.y -= 1 * Time.deltaTime;
transform.position = newPosition;
if (newPosition.y < 1) {
Rise ();
}
}
}
Answer by Lo0NuhtiK · Mar 30, 2014 at 04:43 AM
http://docs.unity3d.com/Documentation/Manual/Coroutines.html
Transform myTrans ;
//how long to keep moving up or down until switching direction
public float verticalTime = 1f ;
//how fast to move vertically
public float verticalSpeed = 5f ;
//how fast to move forward
public float moveSpeed = 10f ;
void Start()
{
myTrans = this.transform ;
StartCoroutine(Rise()) ;
}
void Update()
{
myTrans.Translate(myTrans.forward * moveSpeed * Time.deltaTime) ;
}
IEnumerator Rise()
{
float t = verticalTime ;
while(t > 0f)
{
myTrans.Translate(myTrans.up * verticalSpeed * Time.deltaTime) ;
t -= Time.deltaTime ;
yield return new WaitForEndOfFrame() ;
}
StartCoroutine(Fall()) ;
}
IEnumerator Fall()
{
float t = verticalTime ;
while(t > 0f)
{
myTrans.Translate(-myTrans.up * verticalSpeed * Time.deltaTime) ;
t -= Time.deltaTime ;
yield return new WaitForEndOfFrame() ;
}
StartCoroutine(Rise()) ;
}
This is exactly what I was looking for! $$anonymous$$ind of sucks that I wasted so much time messing with my version only to find out it's completely useless. But hey, that's how we learn, right? :-) Thank you very much!
Your answer
Follow this Question
Related Questions
How to make an object go to pre-seted position in world 1 Answer
Animate 1 object with 5 bones? Or use translate on 5 objects? 1 Answer
Camera rotation around player while following. 6 Answers
Help using Lerp inside of a coroutine. 1 Answer
Changing the player's position in multiplayer mode. 0 Answers