繁体   English   中英

具有2个刚体的统一c#脚本。 当一个刚体放在另一个刚体上时,跳跃不起作用

[英]unity c# script with 2 rigid bodies. jumping not working when one rigid body has been onto of the other

第二个刚体使用与第一个刚体相同的脚本,但是在if实例中使用“&player number == 1”。

问题是,如果第一个刚体跳到另一个刚体上然后跳下,第二个刚体将根本无法跳。 (反之亦然)

有什么简单的解决方案呢?

using UnityEngine;

using System.Collections;

public class PlayerController : MonoBehaviour 
{

//Movement
public float speed;
public float jump;
float moveVelocity;

//Grounded Vars
bool grounded = true;

int playernumber;


void Update () 
{
    if (Input.GetKeyDown (KeyCode.Alpha1)) {
        playernumber = 1;
    }

    if (Input.GetKeyDown (KeyCode.Alpha2)) {
        playernumber = 2;
    }

    if (Input.GetKeyDown (KeyCode.Alpha3)) {
        playernumber = 3;
    }
    //Jumping   
    if ((Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKeyDown (KeyCode.Z) || Input.GetKeyDown (KeyCode.W))  & playernumber == 1  ) 
    {
        if(grounded)
        {
            GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
        }
    }



    moveVelocity = 0;

    //Left Right Movement
    if ((Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A)) & playernumber == 1 ) 
    {
        moveVelocity = -speed;
    }
    if ((Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D)) & playernumber == 1 ) 
    {
        moveVelocity = speed;
    }

    GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveVelocity, GetComponent<Rigidbody2D> ().velocity.y);

}

//Check if on the ground
void OnTriggerEnter2D()
{
    grounded = true;
}
void OnTriggerExit2D()
{
    grounded = false;
}
}

当实际事件发生时,将触发这些触发事件一次 ,因此:

  1. 播放器1和播放器2生成并触摸地板或smt。 沿着那两条线=>触发了onTriggerEnter事件,并且它们都接地
  2. 玩家1跳到玩家2
    • player1跳=> onTriggerExit-不接地
    • 玩家1登陆玩家2 => onTrigger为两个玩家输入射击并且他们都被接地
  3. 玩家1从玩家2跳下=> onTriggerExit都触发-两者都不接地
    • 然后player1摔倒并触发onTriggerEnter,因此他已经接地, 但是player2并不意味着他没有接地所以不能跳

您可以很简单地将用户跳动时将Grounded设置为false,然后仅使用onTriggerEnter将其重置为true并废弃onTriggerExit:

if(grounded){
    GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
    grounded = false;
}

编辑:我没有注意到这两个触发方法都与您的代码中的相应签名不匹配,因为它们错过了Collider2D参数。

void OnTriggerEnter2D(Collider2D collider) {
    grounded = true;
}

暂无
暂无

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

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