简体   繁体   English

角色停止移动,我不知道为什么

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

I had my code working perfectly the character was moving side to side and jumping but I tried to get him to stop jumping twice and he just stopped moving entirely.我的代码完美运行,角色左右移动并跳跃,但我试图让他停止跳跃两次,他只是完全停止移动。 Can you help me figure out what I did wrong?你能帮我弄清楚我做错了什么吗? I have looked this question up but yet to find an answer that makes sense to me (I'm relatively new) so if some can work through this with me I would appreciate it greatly so I can get back to work learning.我已经查看了这个问题,但还没有找到一个对我有意义的答案(我相对较新),所以如果有人能和我一起解决这个问题,我将不胜感激,这样我就可以回去工作学习了。

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;
    }
}

If isGrounded is false, you return right out of the function.如果isGrounded为假,您return直接从 function 中返回。 The last line is also skipped this way.最后一行也以这种方式跳过。 To fix this, you could simply check if isGrounded is true, and only execute the jumping code then (forget return ).要解决这个问题,您可以简单地检查isGrounded是否为真,然后只执行跳转代码(忘记return )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM