I try to make a basic game in Unity for the first time, a 2D platform.
When I want to jump I'm not able to just jump when it hits the ground, it always jumps even though it's not on the platforms, which have the Layer Ground.
This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ControlPersonaje : MonoBehaviour
{
public float velocidadMaxima = 1f;
public float velocidad = 0.5f;
private Rigidbody2D rigi;
private Animator anim;
private bool facingRight;
private bool jump = false;
public float jumpForce=9.9f;
public bool grounded = false;
public Transform pie;
public LayerMask groundLayerMask;
public enum GameState { Idle, Playing };
public GameState gameState=GameState.Idle;
public GameObject uiScore;
private int puntos = 0;
public Text puntosTexto;
public float radio=0.1f;
void Start()
{
uiScore.SetActive(false);
rigi = GetComponent<Rigidbody2D>();
anim = this.GetComponent<Animator>();
facingRight = false;
Flip();
}
void Awake()
{
// Setting up references.
anim = GetComponent<Animator>();
}
void OnCollisionEnter(Collision col){
if(col.gameObject.tag=="Ground"){
grounded=true;
}
}
void Update()
{
if(gameState==GameState.Idle &&(Input.GetKeyDown("up") || Input.GetMouseButtonDown(0))){
gameState=GameState.Playing;
uiIdle.SetActive(false);
uiScore.SetActive(true);
if(Input.GetKeyDown(KeyCode.UpArrow) && (grounded)){
jump=true;
}
}
}
void FixedUpdate()
{ // mejor el fixed update para trabajar con fisicas
if (gameState == GameState.Playing)
{ // si el juego se pone en marcha
movimientoJugador();
}
}
void Flip()
{
Vector3 v;
if (facingRight)
v = Vector3.Slerp(Vector3.right, Vector3.left, 1.0f);
else
v = Vector3.Slerp(Vector3.left, Vector3.right, 1.0f);
facingRight = !facingRight;
transform.rotation = Quaternion.LookRotation(v);
}
void movimientoJugador(){
float mover = Input.GetAxis("Horizontal");
rigi.velocity = new Vector2(mover * velocidadMaxima, rigi.velocity.y);
anim.SetFloat("Speed", Mathf.Abs(mover));
if (Input.GetKeyDown(KeyCode.UpArrow)&& grounded)
jump = true;
if (mover > 0 && !facingRight)
Flip();
if (mover < 0 && facingRight)
Flip();
if (jump) // esto es equivalente a if jump==true
{
// set el trigger del animator para saltar
// añade una fuerza vertical al jugador para que salte
rigi.AddForce(new Vector2(0, jumpForce));
anim.SetBool("Jump",true);
//anim.SetBool("Jump",false);
// marca que no salte una vez que ya haya saltado
jump = false;
}
}
void OnTriggerEnter2D(Collider2D other) // cuando chocamos contra un enemigo
{
if (other.gameObject.tag == "Point")
{
IncrementarPuntos();
}
}
public void IncrementarPuntos()
{
puntos++;
puntosTexto.text = puntos.ToString();
}
}