second rigid body uses the same script as the first one but with "& player number == 1" in the if-instances.
problem is if the first rigid body jumps on top of the other and then jumps off, the second one will not be able to jump at all. (and vice versa)
what would be a simple solution for this?
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;
}
}
These trigger events are fired once when the actual events occur and thus:
You could quite simply just set the grounded to false when the user jumps and only reset it to true using the onTriggerEnter and scrap the onTriggerExit:
if(grounded){
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
grounded = false;
}
Edit: I failed to notice that both trigger methods don't match their appropriate signatures in your code as they miss a Collider2D parameter.
void OnTriggerEnter2D(Collider2D collider) {
grounded = true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.