Certainly! Here's an example of a simple Unity script that includes player control, jump command, and attack command functionality:
using System.Collections;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 5f;
public Transform groundCheck;
public LayerMask groundLayer;
public float groundCheckRadius = 0.2f;
private Rigidbody2D rb;
private bool isGrounded;
private bool isAttacking;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
// Check if the player is on the ground
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
// Player movement control
float moveDir = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveDir * moveSpeed, rb.velocity.y);
// Jump control
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
// Attack control
if (Input.GetButtonDown("Fire1") && !isAttacking)
{
StartCoroutine(Attack());
}
}
private IEnumerator Attack()
{
isAttacking = true;
// Play attack animation or perform attack action
yield return new WaitForSeconds(0.5f); // Adjust duration as needed
// Reset attack animation or perform subsequent actions
isAttacking = false;
}
}
In this script:
moveSpeed determines the player's movement speed.
jumpForce determines the force applied for jumping.
groundCheck is an empty game object positioned at the player's feet used to check if the player is on the ground.
groundLayer is the layer where the ground objects are placed.
groundCheckRadius is the radius used to check whether the player is on the ground.
rb refers to the Rigidbody2D component attached to the player object.
isGrounded stores whether the player is on the ground or not.
isAttacking stores whether the player is currently attacking or not.
- Input for movement is obtained using
Input.GetAxis("Horizontal"), where the player moves horizontally using the "Horizontal" axis.
- Input for jumping is obtained using
Input.GetButtonDown("Jump"), triggered when the "Jump" button is pressed.
- Input for attacking is obtained using
Input.GetButtonDown("Fire1"), triggered when the "Fire1" button (typically left mouse button) is pressed.
Feel free to adjust the script according to your specific needs and attach it to your player object to enable control, jumping, and attacking functionality!