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

时间:2016-04-23 21:03:01

标签: c# unity3d

我在编写游戏时学习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坐标,这是一种更有效的方法,但我想知道为什么这不起作用。如果有人能教我那么我会很高兴。

1 个答案:

答案 0 :(得分:0)

使用UnityEngine; 使用System.Collections;

public class 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);
    }
}

}