简体   繁体   中英

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. And sorry for my english, I'm not english:P Thanks in advance.

For starters, you should put physics stuff in a FixedUpdate(), and input in Update(), this is untested:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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