Unity5:2D平台游戏:跳到不同的高度

时间:2016-10-27 23:47:48

标签: c# unity3d game-engine game-physics

我正在尝试在C#中实现字符跳转 但我希望他跳到不同的高度,取决于你按住跳跃按钮的日志 例如,如果你瞬间击中太空 - 你不会跳得那么高 相反 - 角色会跳得更高,但是在有限的高位 这是我的代码:

private Rigidbody2D rb;
private Transform lowerPoint;
private new SpriteRenderer renderer;
private Animator anim;
private Transform spawPosition;

[SerializeField]
float speed = 3f;
[SerializeField]
float jumpForce = 3f;
[SerializeField]
Image backgroundImage;
[SerializeField]
LayeredSpikes script;

float secondJumpForce;
[SerializeField]
float additionalVelocity;
const float ADDITION_VELOCITY_LIMIT = 0.9f;

bool isGrounded;
bool isAlive;
bool hasSecondJump;

void Awake()
{
    rb = GetComponent<Rigidbody2D> ();
    renderer = GetComponent<SpriteRenderer> ();
    lowerPoint = GetComponentInChildren<Transform> ();
    anim = GetComponent<Animator> ();
    spawPosition = GameObject.FindGameObjectsWithTag ("Respawn")[0].GetComponent<Transform> ();
}
void Start()
{
    ResetVelocity ();
    isGrounded = false;
    isAlive = true;
    hasSecondJump = true;
    Spawn ();
    secondJumpForce = jumpForce * 0.75f;
}

void Update()
{
    if (isAlive) 
    {
        if (isGrounded) 
        {
            AnimState = AnimationState.Idle;
            hasSecondJump = true;
            additionalVelocity = 0f;
        }

        if (Input.GetButtonDown ("Jump")) 
        {
            Jump ();
        }

        if (Input.GetButton ("Jump")
            && additionalVelocity <= ADDITION_VELOCITY_LIMIT) 
        {
            additionalVelocity += ADDITION_VELOCITY_LIMIT / 3;
            rb.AddForce( Vector2.up * additionalVelocity );
        }

        if (Input.GetButton ("Horizontal")) 
        {
            Run ();
        }
    }
}

private void Jump()
{
    AnimState = AnimationState.Jump;
    float force;

    if (isGrounded) 
    {
        force = jumpForce;
    } 
    else 
    {
        if (hasSecondJump) 
        {
            ResetVelocity ();
            force = secondJumpForce;
            hasSecondJump = false;
        } 
        else 
        {
            force = 0f;
        }
    }
    rb.AddForce (Vector2.up * force, ForceMode2D.Impulse);
    if (force != 0f) 
    {
        //script.Trigger ();
    }
}

void ResetVelocity()
{
    rb.velocity = Vector2.zero;
    additionalVelocity = 0f;
}

我正试图在跳跃中间添加力量,但没有结果。

1 个答案:

答案 0 :(得分:4)

乍一看,我可以观察到你的bool变量 isGrounded 总是 false 。 这个问题很棘手,因为这是你实际工作的第二次跳跃,但不是你的第一次跳跃,这就是你无法检测它的原因!

将变量 isGrounded = true 设置为Start()的默认值,然后当您进行第一次跳转时,设置 isGrounded = false

然后你可以使用碰撞器来检测你的角色何时回到地面,如果是,你需要让你的 isGrounded 变量 public isGrounded

希望我能够提供帮助!

  • 野老