[英]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;
}
}
当实际事件发生时,将触发这些触发事件一次 ,因此:
您可以很简单地将用户跳动时将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.