我的代碼僅適用於水平移動。垂直運動不應該工作嗎?我剛開始學習基本的2D統一規劃:如何在Unity中使用WASD移動2D對象
public class Player : MonoBehaviour {
//These fields will be exposed to Unity so the dev can set the parameters there
[SerializeField] private float speed = 1f;
[SerializeField] private float upY;
[SerializeField] private float downY;
[SerializeField] private float leftX;
[SerializeField] private float rightX;
private Transform _transformY;
private Transform _transformX;
private Vector2 _currentPosY;
private Vector2 _currentPosX;
// Use this for initialization
void Start() {
_transformY = gameObject.GetComponent<Transform>();
_currentPosY = _transformY.position;
_transformX = gameObject.GetComponent<Transform>();
_currentPosX = _transformX.position;
}
// Update is called once per frame
void Update() {
_currentPosY = _transformY.position;
_currentPosX = _transformX.position;
float userInputV = Input.GetAxis ("Vertical");
float userInputH = Input.GetAxis ("Horizontal");
if (userInputV < 0)
_currentPosY -= new Vector2 (0, speed);
if (userInputV > 0)
_currentPosY += new Vector2 (0, speed);
if (userInputH < 0)
_currentPosX -= new Vector2 (speed, 0);
if (userInputH > 0)
_currentPosX += new Vector2 (speed, 0);
CheckBoundary();
_transformY.position = _currentPosY;
_transformX.position = _currentPosX;
}
private void CheckBoundary(){
if (_currentPosY.y < upY)
_currentPosY.y = upY;
if (_currentPosY.y > downY)
_currentPosY.y = downY;
if (_currentPosX.x < leftX)
_currentPosX.x = leftX;
if (_currentPosX.x > rightX)
_currentPosX.x = rightX;
}
}
如果我刪除/註釋掉_currentPosX
,然後我的垂直運動的作品它的相關代碼。但是,如果我刪除/註釋掉_currentPosY
及其相關代碼,則我的「水平」移動將起作用。
但是我怎麼會遇到麻煩讓他們同時工作?我想我只是想念一些東西,但我無法弄清楚,因爲我只是一個初學者。
感謝誰可以給予建議。
編輯:爲進一步澄清...
我編碼一個簡單的2D遊戲,將在使用WASD鍵4方向移動播放器。
W = move up
A = move left
S = move down
D = move right
我的主要問題是,我可以得到兩個只在一個軸工作的關鍵:無論是A和d正在爲水平的,而W和S不工作在所有的垂直運動,反之亦然。
你能描述一下你的控制嗎? WASD用於什麼? – Programmer
只是在2D遊戲畫面(精靈)中向上,向下,向左,向右移動 – 5120bee
對象是否具有rigidbody2d? – Programmer