【问题标题】:making a ball Jump a fixed distance打球 跳一段固定距离
【发布时间】:2018-03-03 16:44:42
【问题描述】:
void Update ()
{
    Vector3 input = new Vector3 (0, 0, 1);
    Vector3 direction = input.normalized;
    Vector3 velocity = direction * speed;
    Vector3 moveAmount = velocity * Time.deltaTime;
    transform.position += moveAmount;

    if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        player.AddForce (Vector3.up * jumpForce, ForceMode.Impulse);
    }
}

由于Time.deltaTime 不同,moveAmount 也因每次跳跃而不同,因此跳跃的距离会略有不同。

球会在由固定间隙隔开的块之间跳跃,因此上述行为会导致问题。

有什么办法可以解决这个问题并进行固定长度的跳跃吗?

【问题讨论】:

  • 不能保证刚体力总是相同的。要减少跳跃距离的差异,请从跳跃距离中删除Time.deltaTime。你不需要那个。

标签: c# unity3d game-physics


【解决方案1】:

您可以为此使用 CharacterController。确保你有一个 CharacterController 和 Collider 附加到你的游戏对象。此外,如果您的游戏对象附加了刚体,它可能会导致其行为异常,因此您可能必须对其进行约束。

public CharacterController controller;

private float verticalVelocity;
private float gravity = 25.0f;
private float jumpForce = 15.0f;

void Awake () {
    controller = GetComponent<CharacterController>();
}

void Update () {

    if( controller == null )
        return;

    if( controller.isGrounded)
    {
        verticalVelocity = -gravity * Time.deltaTime;
        if( Input.GetKeyDown(KeyCode.Space) )
        {
            verticalVelocity = jumpForce;
        }
    }
    else
    {
        verticalVelocity -= gravity * Time.deltaTime;
    }   

    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");    

    Vector3 moveVector = Vector3.zero;
    moveVector.x = moveHorizontal * 5.0f;
    moveVector.y = verticalVelocity;
    moveVector.z = moveVertical * 5.0f;
    controller.Move(moveVector * Time.deltaTime);
} 

查看本教程以供参考:https://www.youtube.com/watch?v=miMCu5796KM

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多