using UnityEngine; public class PlayerMovement : MonoBehaviour { public float maxSpeed; public float jumpPower; Rigidbody2D rigid; SpriteRenderer spriteRenderer; Animator anim; void Awake() { rigid = GetComponent(); spriteRenderer = GetComponent(); anim = GetComponent(); } void Update() { bool grounded = anim.GetBool("isGrounded"); if (Input.GetButtonDown("Jump") && grounded) { rigid.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse); anim.SetBool("isGrounded", false); } // Flip sprite direction if (Input.GetButtonDown("Horizontal")) { spriteRenderer.flipX = Input.GetAxisRaw("Horizontal") == -1; } // Animation: running (only when grounded) anim.SetBool("isRunning", Mathf.Abs(rigid.linearVelocity.x) > 0.3f && grounded); } void FixedUpdate() { float h = Input.GetAxisRaw("Horizontal"); // Directly set velocity for tighter control and no sliding Vector2 velocity = rigid.linearVelocity; velocity.x = h * maxSpeed; rigid.linearVelocity = velocity; // Ground check with raycast Debug.DrawRay(rigid.position, Vector2.down * 1f, Color.green); RaycastHit2D rayhit = Physics2D.Raycast(rigid.position, Vector2.down, 1f, LayerMask.GetMask("ground")); if (rayhit.collider != null) { anim.SetBool("isGrounded", true); } else { anim.SetBool("isGrounded", false); } } void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "enemy") { Debug.Log("Ouch"); } } }