UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"2d platformer character controller"
using UnityEngine; public class PlatformerCharacterController2D : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 7f; public LayerMask groundLayer; private Rigidbody2D rb; private bool isGrounded; private float horizontalInput; private Vector3 velocity = Vector3.zero; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { horizontalInput = Input.GetAxis("Horizontal"); if (Input.GetButtonDown("Jump") && isGrounded) { Jump(); } } void FixedUpdate() { Move(); CheckGround(); } void Move() { Vector3 targetVelocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y); rb.velocity = Vector3.SmoothDamp(rb.velocity, targetVelocity, ref velocity, 0.05f); } void Jump() { rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse); } void CheckGround() { RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 0.1f, groundLayer); if (hit.collider != null) { isGrounded = true; } else { isGrounded = false; } } }