簡體   English   中英

我的碰撞2d在Unity上的C#中不起作用

[英]my collision 2d doesn't work in C# on Unity

我在編寫游戲編程時正在學習C#,但我一直堅持做這項運動。 我希望我的角色通過按一次“ D”或“ A”連續移動。 然后,在向右移動時與一個隱形牆碰撞后,向后走,直到撞到另一個隱形牆並停止。 我設法使GameObject移動,但是當它與牆碰撞時,什么也沒發生。 這兩個對象都有一個rigidbody2D ,相同的z坐標和正確的標簽。

public class SquadMovement : MonoBehaviour {

    float speed;
    bool collisionRightWall = false;

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

        if (Input.GetKeyDown (KeyCode.D)) {  

            CancelInvoke ();
            InvokeRepeating ("RightMovement", Time.deltaTime, Time.deltaTime);

        }

        if (Input.GetKeyDown (KeyCode.A)) {

            CancelInvoke ();
            InvokeRepeating ("LeftMovement", Time.deltaTime, Time.deltaTime);

        }
    }

    void RightMovement () {

        speed = 10f;
        transform.Translate (speed * Time.deltaTime, 0, 0);

    }

    void LeftMovement () {

        speed = -7f;
        transform.Translate (speed * Time.deltaTime, 0, 0);

    }

    void OnCollisionWallR (Collider2D colR) {

        if (colR.gameObject.tag == "invisibleWallRight") {

            collisionRightWall = true;
            Debug.Log (collisionRightWall);

        }
    }
}

我正在使用不可見的牆,因為我不知道如何使用x坐標。有一種更有效的方法,但是我想首先知道為什么它不起作用。 如果有人也能教我我會很高興。

使用UnityEngine; 使用System.Collections;

公共課SquadMovement:MonoBehaviour {

float constantspeed = 3;
float speed;

//Key inputs

void Update () {

    transform.Translate (constantspeed * Time.deltaTime, 0, 0);
    if (Input.GetKeyDown (KeyCode.D)) {  

        StopAllCoroutines ();
        StartCoroutine (RightMovement(0f));
    }

    if (Input.GetKeyDown (KeyCode.A)) {

        StopAllCoroutines ();
        StartCoroutine (LeftMovement(0f));
    }
}

//Movement itself (Right, Left)

IEnumerator RightMovement (float Rloop) {

    while (transform.position.x < Time.time * constantspeed + 6) {

        speed = 10f;
        transform.Translate (speed * Time.deltaTime, 0, 0);
        yield return new WaitForSeconds (Rloop);
    }

    if (transform.position.x > Time.time * constantspeed + 5.9) {

        StopAllCoroutines ();
        StartCoroutine (LeftMovement (0f));
    }
}

IEnumerator LeftMovement (float Lloop) {

    while (transform.position.x > Time.time * constantspeed -8) {

        speed = -7f;
        transform.Translate (speed * Time.deltaTime, 0, 0);
        yield return new WaitForSeconds (Lloop);
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM