如何让玩家上下跳动?

时间:2014-12-23 07:28:39

标签: c# unity3d 2d

我正在制作一个非常简单的安卓游戏,但我是编码的新手。我希望我的播放器能够在屏幕上不停地上下移动,但不能让它变成黑客。

public class DuckBehaviour : MonoBehaviour {

Vector3 velocity = Vector3.zero;
float speed = 1f;
float verticality;



// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

    if (transform.position.y < Screen.height -10) {
        velocity.y = 0.7f;
    } else if (transform.position.y > 10) {
        velocity.y = -0.7f;
    }
    transform.position += velocity * Time.deltaTime;
}
}

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情(取自Unity论坛 - see here。 请注意,代码实际上没有经过测试:)

public class DuckBehaviour : MonoBehaviour {

 float speed = 1f;
 float verticality;
 Vector3 pointB;

 IEnumerator Start () {
    Vector3 pointA = transform.position;
    while (true) {
       yield return StartCoroutine(MoveObject(transform, pointA, pointB, 3.0));
       yield return StartCoroutine(MoveObject(transform, pointB, pointA, 3.0));
    }
  }

 IEnumerator MoveObject (Transform thisTransform, Vector3 startPos, Vector3 endPos, float time) {
     float i = 0.0f;
     float rate = 1.0f / time;
     while (i < 1.0f) {
         i += Time.deltaTime * rate;
         thisTransform.position = Vector3.Lerp(startPos, endPos, i);
         yield return null; 
      }
   }

 }

C#要求您使用StartCoroutine方法,并且任何用作协同程序的方法都必须返回IEnumerator。此页面解释了how coroutines work

答案 1 :(得分:0)

代码似乎有两个问题。第一个是如果游戏对象在屏幕上开始而不是在屏幕外,则其速度将保持在Vector2.zero。第二个问题是Screen.height以像素为单位,但转换是在Unity的单位。希望这会有所帮助。

public class DuckBehaviour : MonoBehaviour {

Vector3 velocity = Vector3.zero;
float speed = 1f;
float verticality;



// Use this for initialization
void Start () {
    velocity.y = 0.7f;
}

// Update is called once per frame
void Update () {
    //Requires that an orthographic camera named "MainCamera" exists with y transform of 0
    if (transform.position.y < -Camera.main.orthographicSize) {
        velocity.y = 0.7f;
    } else if (transform.position.y > Camera.main.orthographicSize) {
        velocity.y = -0.7f;
    }
    transform.position += velocity * Time.deltaTime;
}
}