简体   繁体   English

如何在 Unity 中使用 WASD 移动 2D 对象

[英]How to move 2D Object with WASD in Unity

My code below only works for horizontal movement.我下面的代码仅适用于水平移动。 Shouldn't the vertical movement be working too?垂直运动不应该也起作用吗? I'm just starting out with basic 2D Unity programming:我刚刚开始学习基本的 2D Unity 编程:

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;
    }
}

If I remove/comment out the _currentPosX and it's related codes then my Vertical movement works.如果我删除/注释掉_currentPosX及其相关代码,那么我的垂直移动就会起作用。 But if I remove/comment out the _currentPosY and it's related codes then my Horizontal movement works.但是,如果我删除/注释掉_currentPosY及其相关代码,那么我的水平移动就会起作用。

But how come I'm having trouble getting them to work at the same time?但是为什么我无法让它们同时工作呢? I think I'm just missing something but I can't figure it out since I'm just a beginner at this.我想我只是错过了一些东西,但我无法弄清楚,因为我只是这方面的初学者。

Thanks to whoever can give advise.感谢哪位能给点建议。

EDIT: for further clarification...编辑:为了进一步澄清......

I'm coding a simple 2d game that will have the player move in 4-directions using the WASD keys.我正在编写一个简单的 2d 游戏,让玩家使用 WASD 键在 4 个方向上移动。

W = move up
A = move left
S = move down
D = move right

My main problem is that I can get two of the keys working only in one axis: either A and D is working for Horizontal while W and S are not working at all for Vertical movement or vice-versa.我的主要问题是我只能让两个键在一个轴上工作:A 和 D 用于水平移动,而 W 和 S 根本不适用于垂直移动,反之亦然。

You don't need those if statements.你不需要那些if语句。 Just use += to append the input to the current transform position.只需使用+=将输入附加到当前变换位置。

Move without Rigidbody :Rigidbody移动:

public float speed = 100;
public Transform obj;

public void Update()
{
    float h = Input.GetAxis("Horizontal");
    float v = Input.GetAxis("Vertical");

    Vector3 tempVect = new Vector3(h, v, 0);
    tempVect = tempVect.normalized * speed * Time.deltaTime;

    obj.transform.position += tempVect;
}

Move Object with Rigidbody2D :使用Rigidbody2D移动对象:

public float speed = 100;
public Rigidbody2D rb;

public void Update()
{
    float h = Input.GetAxis("Horizontal");
    float v = Input.GetAxis("Vertical");

    Vector3 tempVect = new Vector3(h, v, 0);
    tempVect = tempVect.normalized * speed * Time.deltaTime;
    rb.MovePosition(rb.transform.position + tempVect);
}

I suggest using the second code and moving the Rigidbody if you want to be able to detect collison later on.如果您希望稍后能够检测到碰撞,我建议使用第二个代码并移动 Rigidbody。

Note :注意

You must assign the object to move to the obj slot in the Editor.您必须指定要移动到编辑器中的obj插槽的obj If using the second code, assign the object with the Rigidbody2D to the rb slot in the Editor.如果使用第二个代码,请将具有Rigidbody2D的对象分配给编辑器中的rb插槽。

THIS CODE WORK 100% (you must try it.)此代码 100% 有效(您必须尝试一下。)

public float moveSpeed = 5;


void Start()
{
   
}


 void Update()
{

    if (Input.GetKey(KeyCode.D))
    {
        transform.position += Vector3.right * moveSpeed * Time.deltaTime;
        
    }
    else if (Input.GetKey(KeyCode.A))
    {
        transform.position += Vector3.right * -moveSpeed * Time.deltaTime;
        
    }

    else if (Input.GetKey(KeyCode.W))
    {
        transform.position += Vector3.up * moveSpeed * Time.deltaTime;

    }
    else if (Input.GetKey(KeyCode.S))
    {
        transform.position += Vector3.up * -moveSpeed * Time.deltaTime;

    }
}

Try changing the value 0 in the Vector2 functions to current x/ y position...I ran into a similar problem with my project尝试将 Vector2 函数中的值 0 更改为当前的 x/y 位置......我的项目遇到了类似的问题

if (userInputV < 0) 
        _currentPosY -= new Vector2 (/*current position*/, speed); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM