I’m new here…so if I do something wrong…I’ m sorry. I tried to make a 2d platform game, and i write the code for movement+jump, but my character dosent jump…Can somebodie figure out this code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D myRigidbody;
[SerializeField]
public float speed = 12.0f;
private bool facingRight;
private bool facingLeft;
[SerializeField]
private Transform[] groundPoints;
private float groundRadius;
private LayerMask whatIsGround;
private bool isGrounded;
private bool jump;
private float jumpForce;
// Use this for initialization
void Start() {
facingRight = true;
myRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal") * speed;
isGrounded = IsGrounded();
Debug.Log(jump);
HandleMovement(horizontal);
Flip(horizontal);
}
private void HandleMovement(float horizontal)
{
myRigidbody.velocity = new Vector2(horizontal , myRigidbody.velocity.y); // X = - 1 , y = 0 ;
if(isGrounded && jump)
{
isGrounded = false;
myRigidbody.AddForce(new Vector2(0, jumpForce));
}
if(Input.GetKeyDown(KeyCode.Space))
{
jump = true;
}
}
private void Flip(float horizontal)
{
if(horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private bool IsGrounded()
{
if (myRigidbody.velocity.y <= 0)
{
foreach (Transform point in groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
for (int i = 0; i < colliders.Length; i ++)
{
if(colliders[i].gameObject !=gameObject)
{
return true;
}
}
}
}
return false;
}
}