UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"2d platformer character controller"
using UnityEngine; public class CharacterController2D : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 7f; private bool isGrounded = false; private Rigidbody2D rb2D; private Animator animator; // Start is called before the first frame update void Start() { rb2D = GetComponent<Rigidbody2D>(); animator = GetComponent<Animator>(); } // Update is called once per frame void Update() { float moveInput = Input.GetAxis("Horizontal"); rb2D.velocity = new Vector2(moveInput * moveSpeed, rb2D.velocity.y); if (moveInput != 0) { transform.localScale = new Vector3(Mathf.Sign(moveInput), 1, 1); animator.SetBool("isRunning", true); } else { animator.SetBool("isRunning", false); } if (isGrounded && Input.GetButtonDown("Jump")) { rb2D.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse); isGrounded = false; animator.SetBool("isJumping", true); } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.CompareTag("Ground")) { isGrounded = true; animator.SetBool("isJumping", false); } } }