繁体   English   中英

使用翻译功能[Unity 2D]跳转时遇到的问题

[英]Problem with Jumping with Translate function [Unity 2D]

太好了,我正在尝试编写一个简单的Platformer作为班级的作品,而我在跳跃方面遇到了问题,角色实际上在跳跃,但由于它立即到达了跳跃的顶峰然后逐渐下降,因此它看起来像是一个传送。 ,我想使其更流畅。

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

public class playerMovement : MonoBehaviour {

    public float speed;
    public float jumpForce;
    public bool grounded;
    public Transform groundCheck;
    private Rigidbody2D rb2d;

    // Use this for initialization
    void Start () {
        rb2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update () {
    }

    private void FixedUpdate()
    {
        float moveVertical = 0;
        float moveHorizontal = Input.GetAxis("Horizontal") * speed;
        moveHorizontal *= Time.deltaTime;

        grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

        if (grounded && Input.GetKeyDown("space"))
        {
            moveVertical = Input.GetAxis("Jump") * jumpForce;
            moveVertical *= Time.deltaTime;
        }

        Vector2 move = new Vector2(moveHorizontal, moveVertical);
        transform.Translate(move);
    }
}

问题的答案在下面,但是,有关未来与Unity有关的问题,请在Unity论坛上提问。 随着越来越多的人专注于Unity本身,您将更快地得到更好的答案。

要解决跳跃问题,宁可将垂直运动和水平运动分为两部分,并使用在Start()函数中分配的刚体来处理跳跃。 使用ForceMode.Impulse可获得速度/加速度的即时爆发。

private void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal") * speed;
    moveHorizontal *= Time.deltaTime;

    grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

    if (grounded && Input.GetKeyDown("space"))
    {
        rb2d.AddForce(transform.up * jumpForce, ForceMode.Impulse);
    }

    Vector2 move = new Vector2(moveHorizontal, 0);
    transform.Translate(move);
}

不用在跳跃时设置位置,而是通过以下方式向角色的刚体添加垂直冲力:

if (grounded && Input.GetKeyDown("space"))
{
    moveVertical = Input.GetAxis("Jump") * jumpForce;
    moveVertical *= Time.fixedDeltaTime;
    rb2d.AddForce(moveVertical, ForceMode.Impulse);
}

Vector2 move = new Vector2(moveHorizontal, 0f);

这将使Rigidbody2D处理更改每帧垂直速度的工作。

另外,由于您是在FixedUpdate中而不是Update中进行所有这些计算,因此使用Time.deltaTime没有任何意义。 您应该改用Time.fixedDeltaTime

暂无
暂无

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

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