简体   繁体   English

角色在第一次跳跃时跳得非常高,然后正常跳跃。 我该如何解决? (统一二维)

[英]The character jumps super high at it's first jump, then it jumps normally. How can I fix it? (Unity 2D)

So that's basically the problem here.所以这基本上就是这里的问题。 I'm creating a jump script using physics.我正在使用物理学创建一个跳转脚本。 Here is the code.这是代码。 Any idea on how to fix it?关于如何解决它的任何想法? I haven't tried anything important yet... Just some small changes, as I have no idea what to do.我还没有尝试任何重要的事情......只是一些小的变化,因为我不知道该怎么做。

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

public class Movement : MonoBehaviour
{
bool canjump = false;
void Start()
{

}
void Update()
{
    if (Input.GetKey("left"))
    {
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(-40000 * Time.deltaTime, 0));
    }
    if (Input.GetKey("right"))
    {
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(40000 * Time.deltaTime, 0));
    }
    if (Input.GetKeyDown("up") && canjump == true)
    {
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 4000000 * Time.deltaTime));
    }
}
void OnTriggerEnter2D()
{
    canjump = true;
}
void OnTriggerExit2D()
{
    canjump = false;
}

} }

PD: OnTriggerEnter && Exit are called because I put triggers just above the plattforms. PD:调用 OnTriggerEnter && Exit 是因为我将触发器放在平台上方。 And sorry for my english, I'm not english:P Thanks in advance.对不起我的英语,我不是英语:P 在此先感谢。

For starters, you should put physics stuff in a FixedUpdate(), and input in Update(), this is untested:对于初学者,您应该将物理内容放在 FixedUpdate() 中,并在 Update() 中输入,这是未经测试的:

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

public class Movement : MonoBehaviour
{
    bool jump = false;
    bool canjump = false;
    void Start()
    {

    }

    void FixedUpdate() {
        if(jump) 
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 4000000 * Time.deltaTime));
             jump = false;
       }
    }

    void Update()
    {
        if (Input.GetKey("left"))
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(-40000 * Time.deltaTime, 0));
        }
        if (Input.GetKey("right"))
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(40000 * Time.deltaTime, 0));
        }
        if (Input.GetKeyDown("up") && canjump == true)
        {
             jump = true;
        }
    }
    void OnTriggerEnter2D()
    {
        canjump = true;
    }
    void OnTriggerExit2D()
    {
        canjump = false;
    }
}

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

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