0
我在編程我的遊戲時學習C#,我被困在做運動。我希望我的角色通過按'D'或'A'一次而連續移動。然後,在向右邊碰到一面看不見的牆後,往後走,直到它碰到另一個看不見的牆,然後停下來。 我設法讓我的GameObject
移動,但是當它與牆壁碰撞時,沒有任何反應。兩個對象都有一個rigidbody2D
,相同的z座標和正確的標籤。我的碰撞2d不能在Unity中的C#上工作
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座標,必須有一個更有效的方式,但我首先要知道爲什麼不工作。如果有人能教我,我也會很高興。
那是哪裏撞機觸發後發送回玩家的邏輯是什麼? – gabriel
什麼是CancelInvoke(); InvokeRepeating(「LeftMovement」,Time.deltaTime,Time.deltaTime); ? Update方法自動調用每一幀,您不需要使用InvokeRepeating。並回答你的問題,正如gjttt1所說,只是將OnCollisionWallR(Collider2D colR)更改爲OnCollisionEnter2D(Collision2D colR) –
他正在檢查每幀的輸入,但不是每幀調用一次。 InvokeRepeating僅在按下按鍵的框架上調用。 –