带有两个刚体的unity c#脚本。当一个刚体与另一个刚体碰撞时,跳跃不起作用
第二个刚体使用与第一个刚体相同的脚本,但在if实例中使用“&player number==1” 问题是,如果第一个刚体跳到另一个刚体上,然后跳下,第二个刚体将根本无法跳下。(反之亦然) 对此,什么是简单的解决方案带有两个刚体的unity c#脚本。当一个刚体与另一个刚体碰撞时,跳跃不起作用,c#,C#,第二个刚体使用与第一个刚体相同的脚本,但在if实例中使用“&player number==1” 问题是,如果第一个刚体跳到另一个刚体上,然后跳下,第二个刚体将根本无法跳下。(反之亦然) 对此,什么是简单的解决方案 using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { //Movement public float speed; public float ju
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;
}
}
使用UnityEngine;
使用系统集合;
公共类玩家控制器:单行为
{
//运动
公众浮标速度;
公众浮标跳跃;
浮动速度;
//接地变压器
bool-grounded=true;
int playernumber;
无效更新()
{
if(Input.GetKeyDown(KeyCode.Alpha1)){
playernumber=1;
}
if(Input.GetKeyDown(KeyCode.Alpha2)){
playernumber=2;
}
if(Input.GetKeyDown(KeyCode.Alpha3)){
playernumber=3;
}
//跳跃
if((Input.GetKeyDown(KeyCode.Space)| Input.GetKeyDown(KeyCode.UpArrow)| Input.GetKeyDown(KeyCode.Z)| Input.GetKeyDown(KeyCode.W))&playernumber==1)
{
如果(接地)
{
GetComponent().velocity=newvector2(GetComponent().velocity.x,jump);
}
}
移动速度=0;
//左右运动
if((Input.GetKey(KeyCode.LeftArrow)| | Input.GetKey(KeyCode.A))&playernumber==1)
{
移动速度=-速度;
}
if((Input.GetKey(KeyCode.RightArrow)| | Input.GetKey(KeyCode.D))&playernumber==1)
{
移动速度=速度;
}
GetComponent().velocity=newvector2(moveVelocity,GetComponent().velocity.y);
}
//检查是否在地面上
void OnTiggerEnter2D()
{
接地=正确;
}
void OnTriggerExit2D()
{
接地=假;
}
}
这些触发事件在实际事件发生时触发一次,因此:
- player1跳跃=>onTriggerExit-未接地
- player1降落在player2=>onTriggerEnter为两名玩家开火,他们都被停飞
- 然后player1撞到地板并触发onTriggerEnter,因此他被禁足,但player2并不意味着他没有被禁足,因此不能跳跃
if(grounded){
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
grounded = false;
}
void OnTriggerEnter2D(Collider2D collider) {
grounded = true;
}