如何在Unity 2d中保持恒定速度?

时间:2020-06-11 22:25:33

标签: c# unity3d

我是Unity和C#的新手。我正在努力开发自己的第一款游戏,很多语法使我感到困惑。当我按“ a”或“ d”或方向键时,我试图用力在x轴上移动精灵,但是看来我的精灵并没有以恒定的速度移动。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class playerMovement : MonoBehaviour
{
    public float vel = .5f;
    public float jumpVel = 10f;
    public bool isGrounded = false;
    private Rigidbody2D rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = transform.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        //Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f,0f);
        //transform.position += move * Time.deltaTime * vel;
        if(Input.GetAxisRaw("Horizontal") == 1){
            rb.AddForce(Vector2.right*vel, ForceMode2D.Force);
        }else if(Input.GetAxisRaw("Horizontal") == -1){
            rb.AddForce(Vector2.right*-vel, ForceMode2D.Force);
        }
        if(Input.GetKeyDown(KeyCode.Space) && isGrounded == true){
            rb.velocity = Vector2.up * jumpVel;
        }

    }
}

1 个答案:

答案 0 :(得分:2)

这是因为您正在使用rb.AddForce向其添加力量,因此每次演奏时都会增加速度,对于玩家的移动,我建议使用CharacterMovement组件,但是如果要使用我能想到的最好的解决方案是:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class playerMovement : MonoBehaviour
{
    public float vel = .5f;
    public float jumpVel = 10f;
    public bool isGrounded = false;
    private Rigidbody2D rb;
    public float maxvel = 10f;

    // Start is called before the first frame update
    void Start()
    {
        rb = transform.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        //Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f,0f);
        //transform.position += move * Time.deltaTime * vel;
        if(Input.GetAxisRaw("Horizontal") == 1 &&rb.velocity.x<=maxvel){
            rb.AddForce(Vector2.right*vel, ForceMode2D.Force);
        }else if(Input.GetAxisRaw("Horizontal") == -1 && rb.velocity.x>=-maxvel){
            rb.AddForce(Vector2.right*-vel, ForceMode2D.Force);
        }
        if(Input.GetKeyDown(KeyCode.Space) && isGrounded == true){
            rb.velocity = Vector2.up * jumpVel;
        }

    }
}

所以,在这个答案中,浮子maxvel(代表最大速度),这个浮子用来知道你想要在哪儿做idoneus速度(你应该自己调整它,我只是为代码工作提供了一些参考) ,我还调用了rb.velocity.x来检查水平轴上的实际速度,所以我决定不直接更改该速度,因为那样会使它从0变为您所放置的速度,使用addforce使其工作平稳;

相关问题