My character jump and is working, but if I press the Jump button several times not to jump infinitely.
think I figured out the mechanism of the flappy bird.
Code i have written is here :
can i help me.
using UnityEngine;
public class CharacterControllerScript : MonoBehaviour {
public float MaxSpeed = 10f;
bool facingRight = true;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public float jumpForce = 1000f;
public bool Jump = false;
private Animator anim;
// Use this for initialization
void Awake () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate () {
grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
anim.SetBool("Ground", grounded);
anim.SetFloat("Vspeed", GetComponent<Rigidbody2D>().velocity.y);
float Move = Input.GetAxis("Horizontal");
anim.SetFloat("Speed", Mathf.Abs(Move));
GetComponent<Rigidbody2D>().velocity = new Vector2(Move * MaxSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (Move > 0 && !facingRight)
Flip();
else if (Move < 0 && facingRight)
Flip();
if (Jump) {
anim.SetBool("Ground", false);
GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce));
Jump = false;
}
}
void Update()
{
if (Input.GetButtonDown("Jump") && grounded)
Jump = true;
/*if (grounded && Input.GetKeyDown(KeyCode.Space))
{
anim.SetBool("Ground", false);
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
}*/
}
void Flip(){
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}