【问题标题】:Buggy Unity "jump" mechanicBuggy Unity“跳跃”机制
【发布时间】:2021-11-13 00:44:28
【问题描述】:

我是使用 C# 和 Unity 编码的新手,我的第一人称游戏一直存在问题,特别是我的角色的跳跃机制。有时角色会跳跃,有时他不会,有时他会做一个小跳跃,我不知道代码有什么问题。我将跳跃脚本与其他移动机制分开编写,因为坦率地说,其余的移动代码绝对是一团糟。

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

public class Jump : MonoBehaviour
{
private CharacterController controller;

private float verticalVelocity;
private float gravity = 14f;
private float jumpForce = 10f;

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

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

    Vector3 moveVector = new Vector3(0, verticalVelocity, 0);
    controller.Move(moveVector * Time.deltaTime);
}
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    如果您有 2 个使用 controller.Move() 的脚本,那肯定会导致一些问题。您需要 1 个脚本来移动 CharacterController

    在我看来,最实用的方法是为 moveX、moveY 和 moveZ 设置一个 Vector3 变量。在计算后将它们相加并将其用于controller.Move()。这是我所说的一个例子:

    direction = Vector3.zero;
    moveX = transform.right * Input.GetAxis("Horizontal") * speed;
    moveY = new Vector3(0, vely, 0);
    moveZ = transform.forward * Input.GetAxis("Vertical") * speed;
    
    direction = moveX + moveY + moveZ;
    
    controller.Move(direction * Time.deltaTime);
    

    在这里的某个地方,您可以通过某种方式修改 vely 或 moveY 来添加跳跃功能。

    【讨论】:

      猜你喜欢
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      相关资源
      最近更新 更多