首页 > 解决方案 > 我在跳跃时遇到玩家移动问题

问题描述

我面临的唯一问题是玩家只有在他们建立动力时才会跳跃,我不希望玩家在站立或移动时通过按空间跳跃我尝试了velocity.y = jumphight这也不起作用

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

public class PlayerMovment : MonoBehaviour
{ 
    public CharacterController controller;
    public float speed = 12f;
    public float gravity = -9.81f;
    Vector3 velocity;
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    bool isGrounded;
    public float JumpHight = 3f;


    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
        if(isGrounded && velocity.y<0)
        {
            controller.slopeLimit = 45.0f;
            velocity.y = -2f;//when player is grounded it just put some gravity to him all the time
        }
        float x = Input.GetAxis("Horizontal");//moves left and right
        float z = Input.GetAxis("Vertical");//moves up and down
        Vector3 move = transform.right * x + transform.forward * z;
        controller.Move(move*speed*Time.deltaTime);
        if(Input.GetButtonDown("Jump") && controller.isGrounded)
        {


            velocity.y = Mathf.Sqrt(JumpHight * -2f * gravity);
        }
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);




    }
}

标签: c#visual-studiounity3d

解决方案


你可以使用 ForceMode force 在刚体上使用 addforce ,如果你不希望你的物理依赖于 fps 使用 FixedUpdate 而不是 update

   GetComponent<Rigidbody>().AddForce(Vector3.up,ForceMode.Force);

推荐阅读