移動ボタンを同時押しで、斜め移動を実装したい。(unity2D)(C#)
移動ボタンを2つ同時押しして、斜め移動ができるようにしたいです。斜め移動もif文で、縦移動や横移動と同様のコードを書こうとも思ったのですが、スマートな方法ではないなと思いました。どのようなコードを実装すれば良いのでしょうか?
- ▲▲機能を動作するようにする
前提
以下のコードで、2Dにおいて、プレイヤーを操作できるようにしましたが、このコードではボタンを同時押しすることで斜め移動することはできませんでした。縦か横にしか動きません。
発生している問題・エラーメッセージ
特になし
該当のソースコード
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class PlayerControll : MonoBehaviour 6{ 7 private Rigidbody2D myRigidBody; 8 9 public float playerSpeedX = 10; 10 public float playerSpeedY = 10; 11 12 // Start is called before the first frame update 13 void Start() 14 { 15 myRigidBody = this.gameObject.GetComponent<Rigidbody2D>(); 16 } 17 18 // Update is called once per frame 19 void Update() 20 { 21 Vector2 force = Vector2.zero; 22 23 if (Input.GetKey(KeyCode.W)) 24 { 25 force = new Vector2(0,playerSpeedY); 26 } 27 28 if (Input.GetKey(KeyCode.A)) 29 { 30 force = new Vector2(playerSpeedX * -1, 0); 31 } 32 33 if (Input.GetKey(KeyCode.S)) 34 { 35 force = new Vector2(0,playerSpeedY * -1); 36 } 37 38 if (Input.GetKey(KeyCode.D)) 39 { 40 force = new Vector2(playerSpeedX, 0); 41 } 42 43 myRigidBody.MovePosition(myRigidBody.position + force * Time.fixedDeltaTime); 44 45 } 46}
試したこと
特になし
補足情報(FW/ツールのバージョンなど)
Unityのバージョン
unity 2021.3.20f1
C#について
visual studio 2019
回答1件
あなたの回答
tips
プレビュー