团结-人物跌倒比跳跃快

时间:2019-11-11 21:25:09

标签: unity3d

我正在尝试为角色实现自己的重力。 但是由于某些我不知道的原因,角色的着陆速度比跳跃时的着陆速度要高得多(初始跳跃速度约为15,最终陆地速度约为24)。我最终尝试复制下面gif上显示的行为。

https://imgur.com/a/q77w5kS

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

public class Movement : MonoBehaviour {
    public float speed = 3;
    public float jumpSpeed = 15;
    public float gravity = -1f;


    private float ySpeed = 0;
    private float jumpTime = 0;
    private bool direction = false; //true for going up, false for falling down - gravity
    private bool previousDirection = false; //to keep track of changing direction

    private CharacterController _characterController;
    // Start is called before the first frame update
    void Start() {
        _characterController = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update() {
        float dx = Input.GetAxis("Horizontal");
        float dz = Input.GetAxis("Vertical");
        float dy = Input.GetAxis("Jump");

//        move around        
        Vector3 movement = new Vector3(dx, 0, dz);

//        limit diagonal movement
        movement = Vector3.ClampMagnitude(movement, 1);
//        speed
        movement *= speed;


//        change of direction
        if(ySpeed>0 && direction!=true)
            direction = true;
        else if(ySpeed<0 && direction!=false)
            direction = false;

//        if changed direction - peak of the jump
        if(direction!=previousDirection){
            Debug.Log("Jump Time = " + jumpTime);
            jumpTime = Time.deltaTime;
            previousDirection = direction;
        }

//        jump/on ground
        if(_characterController.isGrounded) {
            ySpeed = -0.5f;
            jumpTime = 0;

            if(dy > 0f){
                ySpeed = jumpSpeed;
            }
        }
//        gravity - when not on ground
        else{
//            dv/dt
            ySpeed += gravity*jumpTime;
//            add jump time
            jumpTime += Time.deltaTime;

            // Debug.Log(jumpTime);
            Debug.Log(ySpeed);
        }

        movement.y = ySpeed;

//        direction adjustment
        movement = transform.TransformDirection(movement);

        movement *= Time.deltaTime;
        _characterController.Move(movement);
    }

}

1 个答案:

答案 0 :(得分:0)

我想我知道我的想法出了什么问题。 ySpeed += gravity*jumpTime

因此,每一帧我都在增加向下的加速度。这应该是:ySpeed += gravity *Time.deltaTime (由于重力的作用,加速度是恒定的,随着时间的流逝不会增大)

它被集成了许多步骤,因此每个Update()周期都是一个时间片,它根据重力引起的加速度增加一定的速度,再乘以该小片所花费的时间。

换句话说... 重力是恒定的加速度。我使它成为空气中时间的线性函数。因此,我在没有重力的情况下开始跳跃,在非常重的重力下结束了跳跃。