简体   繁体   English

跳跃无法按预期运行Unity 3D

[英]Jumping Is Not Working As Expected Unity 3D

Hello I am trying to figure out why my jumping is inconsistent. 您好,我试图弄清楚为什么我的跳跃不一致。 I've looked at many StackOverflow questions and I still can't find a solution. 我看了很多StackOverflow问题,但仍然找不到解决方案。 If someone could help that would be amazing! 如果有人可以帮助,那将是惊人的! :D :D

using UnityEngine;
using System.Collections;

public class BallMovement : MonoBehaviour {

public float speed;

private Rigidbody rb;

void Start ()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate ()
{
    Camera mainCamera = GameObject.FindGameObjectWithTag("8BallCamera").GetComponent<Camera>() as Camera;
    float moveHorizontal = Input.GetAxisRaw ("Horizontal");
    float moveVertical = Input.GetAxisRaw("Vertical");
    Vector3 movement = mainCamera.transform.forward * moveVertical * 30;
    rb.AddForce (movement * speed);

    if (Input.GetKeyDown("space")) {
        rb.AddForce(0,2f,0, ForceMode.Impulse);
    }
}

}

When asking a question, try to be more detailed on the facts of the issue, as phrases like "not working as expected" and "jumping is inconsistent" is pretty subjective, and could mean something different depending who reads it :) 提出问题时,请尝试更详细地说明问题的事实,因为诸如“未按预期方式工作”和“跳跃不一致”之类的主观说法很主观,并且可能因读者而有所不同:)

I tried out the code on my machine, and found that sometimes pressing the space bar would not initiate the jump. 我在计算机上试用了代码,发现有时按空格键不会启动跳转。 No other issues seemed to arise (although you may want to place in a cooldown for your jump later on). 似乎没有其他问题出现(尽管您可能希望放置一个冷却时间,以便稍后跳转)。

The issue was with your jump codes being in FixedUpdate() . 问题在于您的跳转代码位于FixedUpdate()中 FixedUpdate() seems to run before Update() , but it's not always called. FixedUpdate()似乎在Update()之前运行,但并不总是调用它。 This is why the space input was sometimes unnoticed. 这就是为什么有时不注意空间输入的原因。

Placing it inside Update() will fix the issue. 将其放在Update()中将解决此问题。

using UnityEngine;
using System.Collections;

public class BallMovement : MonoBehaviour
{

    public float speed;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        Camera mainCamera = GameObject.FindGameObjectWithTag("8BallCamera").GetComponent<Camera>() as Camera;
        float moveHorizontal = Input.GetAxisRaw("Horizontal");
        float moveVertical = Input.GetAxisRaw("Vertical");
        Vector3 movement = mainCamera.transform.forward * moveVertical * 30;
        rb.AddForce(movement * speed);

        if (Input.GetKeyDown("space"))
        {
            rb.AddForce(0, 2f, 0, ForceMode.Impulse);
        }
    }
}

Hope this helps! 希望这可以帮助!

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

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