簡體   English   中英

角色停止移動,我不知道為什么

[英]Character Stopped Moving and I Don't Know Why

我的代碼完美運行,角色左右移動並跳躍,但我試圖讓他停止跳躍兩次,他只是完全停止移動。 你能幫我弄清楚我做錯了什么嗎? 我已經查看了這個問題,但還沒有找到一個對我有意義的答案(我相對較新),所以如果有人能和我一起解決這個問題,我將不勝感激,這樣我就可以回去工作學習了。

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

public class Player : MonoBehaviour

{
  bool jumpKeyWasPressed;
  float horizontalInput;
  Rigidbody rigidBodyComponent;
  bool isGrounded;

    // Start is called before the first frame update
    void Start()
    {
        rigidBodyComponent = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
    //Space key input
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpKeyWasPressed = true;   
        }

        horizontalInput = Input.GetAxis("Horizontal");
    }

    //main problem I think
    void FixedUpdate ()
    {
            if (!isGrounded)
        {
            return;
        }

        if (jumpKeyWasPressed)
        {
            rigidBodyComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
            jumpKeyWasPressed = false;
        }

        rigidBodyComponent.velocity = new Vector3(horizontalInput,rigidBodyComponent.velocity.y, 0);
    }
 
    void OnCollisionEnter(Collision collision)
    {
        isGrounded = true;
    }

    void OnCollisionExit(Collision collision)
    {
        isGrounded = false;
    }
}

如果isGrounded為假,您return直接從 function 中返回。 最后一行也以這種方式跳過。 要解決這個問題,您可以簡單地檢查isGrounded是否為真,然后只執行跳轉代碼(忘記return )。

if (isGrounded) {
    if (jumpKeyWasPressed) {
        // ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM