简体   繁体   English

如何在输入上增加/减少速度?

[英]How to increment/decrement speed on input?

I want to increment and decrement the speed on object movement with input. 我想通过输入来增加和减少对象移动的速度。 What would the best way to go about this? 最好的方法是什么?

Since there is no code i ll try my best to explain, whenever you are pressing down a key you can increase a variable and whenever you press another key you can decrease the variable. 由于没有代码,我将尽力解释,每当您按下一个键时,您可以增加一个变量,而当您按下另一个键时,您可以减少该变量。 This should be done in the Update() method and it can go something like this 这应该在Update()方法中完成,它可以像这样

void Update()
{
    if (Input.GetKeyDown("a"))
    {
        variable++;
    }
    else if (Input.GetKeyDown("b"))
    {
        variable--;
    }
}

The best way to go really depends on the features that you want to implement in your game and how you want the object movement to feel. 最好的方法实际上取决于您要在游戏中实现的功能以及希望物体运动的感觉。

This is one way to do exactly what you asked though 这是一种完全按照您的要求做的方法

using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerMovement : MonoBehaviour {

    private Rigidbody2D rigidbody2D;
    private Vector2 velocity;
    public float playerMoveSpeed = 6; //the value that you want

    private float HorizontalMov;
    private float VerticalMov;

    void Awake() {
        rigidbody2D = this.GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        HorizontalMov = Input.GetAxis("Horizontal") * playerMoveSpeed * Time.deltaTime;
        VerticalMov = Input.GetAxis("Vertical") * playerMoveSpeed * Time.deltaTime;
        AddVelocity(new Vector2(HorizontalMov, VerticalMov));
        rigidbody2D.velocity = velocity;
    }

    public void AddVelocity(Vector2 newVelocity) {
        velocity += newVelocity;
    }

}

You can learn more about Input.GetAxis and RigidBody2D.velocity in the unity documentation 您可以在统一文档中了解有关Input.GetAxisRigidBody2D.velocity的更多信息。

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

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