using System.Collections; using System.Collections.Generic; using UnityEngine; public…
- User
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MarioController : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 5f; private bool isJumping = false; private bool grounded; private Vector2 direction; private Rigidbody2D rb2d; private new Collider2D collider; private Collider2D[] results;
codeprivate void Awake() { rb2d = GetComponent<Rigidbody2D>(); collider = GetComponent<Collider2D>(); results = new Collider2D[4]; } private void CheckCollision() { grounded = false; Vector2 size = collider.bounds.size; size.y += 0.1f; size.x /= 2f; int amount = Physics2D.OverlapBoxNonAlloc(transform.position, size, 0f, results); for (int i = 0; i < amount; i++) { GameObject hit = results[i].gameObject; if (hit.layer == LayerMask.NameToLayer("Platform")) { grounded = hit.transform.position.y < (transform.position.y - 0.5f); } } } private void Update() { CheckCollision(); if (grounded && Input.GetButtonDown("Jump")) { direction = Vector2.up * jumpForce; } else { direction += Physics2D.gravity * Time.deltaTime; } float movement = Input.GetAxis("Horizontal"); if (grounded) { direction.y = Mathf.Max(direction.y, -1f); } // Move Mario horizontally rb2d.velocity = new Vector2(movement * moveSpeed, rb2d.velocity.y); // Flip Mario’s sprite based on his movement direction if (movement > 0) { transform.localScale = new Vector3(1f, 1f, 1f); // Facing right } else if (movement < 0) { transform.localScale = new Vector3(-1f, 1f, 1f); // Facing left } } //private void OnCollisionEnter2D(Collision2D collision) //{ // Reset jumping when Mario touches the ground //if (collision.gameObject.CompareTag("Platform")) //{ // isJumping = false; //} //} - Assistant
To fix the script and enable Mario to jump, modify the Update() method by adding a condition to check if Mario is grounded before allowing him to jump. Here's the modified script: