Untitled
unknown
plain_text
a year ago
1.5 kB
5
Indexable
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f; // Movement speed
public float jumpForce = 10f; // Jump force
private bool isGrounded; // Check if the player is on the ground
private Rigidbody2D rb; // Reference to the player's Rigidbody2D
void Start()
{
// Get the Rigidbody2D component attached to the player
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
// Get horizontal movement input (A/D or Left/Right arrow keys)
float moveInput = Input.GetAxis("Horizontal");
// Move the player horizontally
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
// Jumping logic (if space bar is pressed and the player is grounded)
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce); // Apply jump force
}
}
// Detect collisions with the ground (or other objects)
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("Ground"))
{
isGrounded = true; // Player is on the ground
}
}
// Detect when the player leaves the ground (e.g., in the air)
void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.CompareTag("Ground"))
{
isGrounded = false; // Player is not on the ground
}
}
}Editor is loading...
Leave a Comment