Dash/Dodge Roll: Thực hiện một cú lướt tới hoặc lăn né nhanh
C# Code
using UnityEngine;
using System.Collections;
public class PlayerDash : MonoBehaviour
{
public float dashSpeed = 20f;
public float dashDuration = 0.2f;
public float dashCooldown = 1f;
private Rigidbody rb;
private Vector3 moveDirection;
private bool canDash = true;
private bool isDashing = false;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Lấy hướng di chuyển từ input
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
moveDirection = new Vector3(horizontal, 0f, vertical).normalized;
if (Input.GetKeyDown(KeyCode.LeftShift) && canDash)
{
StartCoroutine(Dash());
}
}
private IEnumerator Dash()
{
canDash = false;
isDashing = true;
// Lưu vận tốc hiện tại để có thể phục hồi sau khi dash
Vector3 originalVelocity = rb.velocity;
// Áp dụng lực dash
rb.velocity = moveDirection * dashSpeed;
// Chờ hết thời gian dash
yield return new WaitForSeconds(dashDuration);
isDashing = false;
rb.velocity = originalVelocity; // Tùy chọn: có thể set rb.velocity = Vector3.zero;
// Bắt đầu cooldown
yield return new WaitForSeconds(dashCooldown);
canDash = true;
}
}Cho phép nhân vật thực hiện một cú lướt nhanh theo hướng di chuyển hiện tại. Có cooldown để tránh lạm dụng.