繁体   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