2017-10-02 7 views
0

Unity(2d)でのプレイヤーの動きを表すこのスクリプト。代わりに、斜めに移動させる - - 2つの方向キーが押され対角線移動を止めるには - Unity 2d?

私が最も最近の方向を押す(そしてそれが解放されている場合、すでにダウン開催の方向)に移動するプレーヤーが必要

if (!attacking) 
{ 
    if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f) 
    { 
     //transform.Translate (new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f)); 
     myRigidBody.velocity = new Vector2(Input.GetAxisRaw("Horizontal") * currentMoveSpeed, myRigidBody.velocity.y); 
     PlayerMoving = true; 
     lastMove = new Vector2(Input.GetAxisRaw("Horizontal"), 0f); 
    } 

    if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f) 
    { 
     //transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") * moveSpeed * Time.deltaTime, 0f)); 
     myRigidBody.velocity = new Vector2(myRigidBody.velocity.x, Input.GetAxisRaw("Vertical") * currentMoveSpeed); 
     PlayerMoving = true; 
     lastMove = new Vector2(0f, Input.GetAxisRaw("Vertical")); 
    } 
} 
+1

は、以前の値を覚えて、プライベート変数のカップルを追加し、比較しますか?これを処理する方法に関する基本的なアイデアを探しているのですか、それをコーディングするのに問題がありますか? –

答えて

2

私はそれをどのように扱うのですか:1つの軸だけがアクティブ(水平または垂直)である場合、その方向を覚えておいてください。両方がある場合は、そうでないものに優先順位を付けます。次のコードは、説明したとおりに機能しますが、他の要件に合わせて調整する必要があります。

void Update() 
{ 
    float currentMoveSpeed = moveSpeed * Time.deltaTime; 

    float horizontal = Input.GetAxisRaw("Horizontal"); 
    bool isMovingHorizontal = Mathf.Abs(horizontal) > 0.5f; 

    float vertical = Input.GetAxisRaw("Vertical"); 
    bool isMovingVertical = Mathf.Abs(vertical) > 0.5f; 

    PlayerMoving = true; 

    if (isMovingVertical && isMovingHorizontal) 
    { 
     //moving in both directions, prioritize later 
     if (wasMovingVertical) 
     { 
      myRigidBody.velocity = new Vector2(horizontal * currentMoveSpeed, 0); 
      lastMove = new Vector2(horizontal, 0f); 
     } 
     else 
     { 
      myRigidBody.velocity = new Vector2(0, vertical * currentMoveSpeed); 
      lastMove = new Vector2(0f, vertical); 
     } 
    } 
    else if (isMovingHorizontal) 
    { 
     myRigidBody.velocity = new Vector2(horizontal * currentMoveSpeed, 0); 
     wasMovingVertical = false; 
     lastMove = new Vector2(horizontal, 0f); 
    } 
    else if (isMovingVertical) 
    { 
     myRigidBody.velocity = new Vector2(0, vertical * currentMoveSpeed); 
     wasMovingVertical = true; 
     lastMove = new Vector2(0f, vertical); 
    } 
    else 
    { 
     PlayerMoving = false; 
     myRigidBody.velocity = Vector2.zero; 
    } 
} 

例の結果(ピンクの線があるlastMove): Result

関連する問題