对象跳转不正确C#

问题描述 投票:0回答:1

我正在尝试统一制作一个 tilemap 平台游戏。对于角色,我正在使用 box collider 2d 和 rigidbody。对于地面,我正在使用带有复合对撞机的 tilemap 对撞机。这是我的脚本

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

public class CharecterScript : MonoBehaviour
{
    public Rigidbody2D rb;
    public float moveSpeed;
    public float jumpHeight;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow)){
            rb.velocity += new Vector2(1, 0) * moveSpeed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.LeftArrow)){
            rb.velocity += new Vector2(-1, 0) * moveSpeed * Time.deltaTime;
        }
        if (Input.GetKeyDown(KeyCode.UpArrow)){
            rb.velocity += new Vector2(0, jumpHeight) * Time.deltaTime;
        }
    }
}

我的脚本的问题是有时它跳得很高,有时又很低

跳低:

跳高:

我该如何解决?

编辑:- 这与刚体有关吗?我应该用 charectercontroller 替换它吗?以及如何使用字符控制器?

c# unity3d rigid-bodies
1个回答
0
投票

您无法控制

Update()
的速度,因此像
Input.GetKey
这样的东西取决于帧速率,并且每秒可能被调用数百次。最好在输入上放置一个计时器,例如:

float t = 0;

    void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow) && t < 1){
            rb.velocity += new Vector2(1, 0) * moveSpeed * Time.deltaTime;
        }
        t += Time.deltaTime;
        if (t > 1) t = 0;
    }
© www.soinside.com 2019 - 2024. All rights reserved.