unity3d 我应该把Time.deltaTime放到这个代码中吗?如果是的话,我应该怎么做?

x759pob2  于 2022-11-16  发布在  其他
关注(0)|答案(3)|浏览(119)

我不知道天气或不使用时间。deltaTime我认为这将是很好的实现它,但我不知道如何,我已经尝试过,但我搞砸了一些东西

using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float horSpeed;
    [SerializeField] private float vertSpeed;
    private Rigidbody2D rb;
    private bool isJumping;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        // we store the initial velocity, which is a struct.
        var v = rb.velocity;

        

        if (Input.GetKey(KeyCode.Space) && !isJumping)
        {
            v.y = vertSpeed * Time.deltaTime;
            isJumping = true;
        }

        if (Input.GetKey(KeyCode.A))
            v.x = -horSpeed * Time.deltaTime;

        if (Input.GetKey(KeyCode.D))
            v.x = horSpeed * Time.deltaTime;

        if (Input.GetKey(KeyCode.S))
            v.y = -vertSpeed * Time.deltaTime;

        rb.velocity = v;

        if(Input.GetKey(KeyCode.Escape))
            SceneManager.LoadScene(0);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        isJumping = false;
    }

}

当我试图添加它时,我的角色只是移动得非常慢

rxztt3cl

rxztt3cl1#

增加vertSpeed和horSpeed的速度,或者可以使用rb.AddForce()

fzsnzjdm

fzsnzjdm2#

将输入向量与时间相乘。DeltaTime使其与帧速率无关。

k5ifujac

k5ifujac3#

试试我的代码。它没有跳跃,需要刚体和碰撞2D。我使它为2D RPG游戏。

public float speed = 2f;
private Rigidbody2D rb;
private Vector2 moveDelta;
//Inputs
private float x;
private float y;

private void Start()
{
    rb = GetComponent<Rigidbody2D>();      
}

private void FixedUpdate()
{
    //Reset V3
    x = Input.GetAxisRaw("Horizontal");
    y = Input.GetAxisRaw("Vertical");
    moveDelta = new Vector2(x, y);        

    //Facing Toward Mouse
    float dir = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).normalized.x;

    //Rigidbody
    rb.velocity = moveDelta * speed * Time.fixedDeltaTime;

    //Swap side of the sprite
    if(dir > 0)
    {
        transform.localScale = Vector3.one;
    }else if (dir < 0)
    {
        transform.localScale = new Vector3(-1, 1, 1);
    }
}

相关问题