Ive looked through almost every thread with no nothing working. Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveLeftRight : MonoBehaviour
{
public float speed = 5.0f;
public float leftLimit = -5.0f;
public float rightLimit = 5.0f;
public float jumpForce = 10.0f;
public LayerMask groundLayer;
private Rigidbody2D rb;
private bool isGrounded;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
isGrounded = true;
}
}
void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
isGrounded = false;
}
}
void Update()
{
isGrounded = Physics2D.OverlapCircle(transform.position, 0.1f, groundLayer);
transform.position += Vector3.right * Input.GetAxis("Horizontal") * speed * Time.deltaTime;
transform.position = new Vector3(Mathf.Clamp(transform.position.x, leftLimit, rightLimit), transform.position.y, transform.position.z);
grounded
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
}
Everything in the code works as normal. When I set the layer of the object using the script it jumps, only reason im not doing that is because it would infinitely be jumping. The two objects are colliding when I check the contacts in the inspector.
Player inspector
Ground inspector