【问题标题】:How do I keep a constant velocity in Unity 2d?如何在 Unity 2d 中保持恒定速度?
【发布时间】:2020-06-13 16:09:24
【问题描述】:

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

    }
}

【问题讨论】:

标签: c# unity3d


【解决方案1】:

那是因为你是用 rb.AddForce 给它加力的,它每次播放都会增加速度,对于玩家移动,我推荐使用 CharacterMovement 组件,但如果你想使用Rigidbody2d 我能想到的最佳解决方案是:

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 使其工作顺利;

【讨论】:

  • 您可能希望更正示例中的变量声明。你把它拼错为“maxbel”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-12
  • 2021-12-23
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
相关资源
最近更新 更多