简体   繁体   English

unity2d 中的 WASD 运动

[英]WASD movement in unity2d

I'm new to unity and wanted to know how can i set the A and D keys to move me right and left with Rigidbody2D .我是新来的团结,想知道我怎么可以设置Ad键移动我的rightleftRigidbody2D I found this script on a forum but it doesn't seem to work:我在论坛上找到了这个脚本,但它似乎不起作用:

public float speed = 5f;
private float movement = 0f;
private Rigidbody2D rigidBody;
// Use this for initialization
void Start()
{
    rigidBody = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
    movement = Input.GetAxis("Horizontal");
    if (movement > 0f)
    {
        rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f)
    {
        rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
    }
    else
    {
        rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
    }
}

Is there an error being thrown?是否抛出错误?
First thing to check is that whatever you have attached this script to actually has a Rigidbody2D .首先要检查的是,您将此脚本附加到的任何内容实际上都有一个Rigidbody2D

Physics, ie setting rigidbody speeds, should be done in FixedUpdate rather than Update , if you look that up and it seems too confusing right now don't worry, you can get away with this for now.物理,即设置刚体速度,应该在FixedUpdate而不是Update ,如果你FixedUpdate一下,现在看起来太混乱了,别担心,你现在可以摆脱这个。

Perhaps you should try using rb.AddForce(movement * speed, ForceMode2D.Impluse);也许你应该尝试使用rb.AddForce(movement * speed, ForceMode2D.Impluse); . .

Since the var movement will actually be positive or negative depending on what key you press, the first two bits of the if statements don't have any use.由于 var movement实际上是正的或负的取决于您按下的键,因此 if 语句的前两位没有任何用处。

Try out looking at this for a single tutorial about moving the player.尝试寻找这个有关移动玩家一个教程。

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

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