UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Character controller with hollow knight like movement like wall jumping or dash"
using UnityEngine; public class HollowKnightController : MonoBehaviour { public float speed = 10.0f; public float jumpForce = 5.0f; public float wallJumpForce = 7.0f; public float dashSpeed = 20.0f; public float dashDuration = 0.2f; public LayerMask wallLayer; private Rigidbody2D rb; private bool isGrounded; private bool isTouchingWall; private bool isDashing; private float dashTime; private Vector2 wallJumpDirection; void Start() { rb = GetComponent<Rigidbody2D>(); wallJumpDirection = new Vector2(1, 2).normalized; } void Update() { float move = Input.GetAxis("Horizontal"); if (!isDashing) { rb.velocity = new Vector2(move * speed, rb.velocity.y); } if (isGrounded && Input.GetButtonDown("Jump")) { rb.velocity = new Vector2(rb.velocity.x, jumpForce); } if (isTouchingWall && !isGrounded && Input.GetButtonDown("Jump")) { rb.velocity = new Vector2(-wallJumpDirection.x * wallJumpForce, wallJumpDirection.y * wallJumpForce); } if (Input.GetButtonDown("Fire1") && !isDashing) { StartCoroutine(Dash()); } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.tag == "Ground") { isGrounded = true; } if (((1 << collision.collider.gameObject.layer) & wallLayer) != 0) { isTouchingWall = true; } } private void OnCollisionExit2D(Collision2D collision) { if (collision.collider.tag == "Ground") { isGrounded = false; } if (((1 << collision.collider.gameObject.layer) & wallLayer) != 0) { isTouchingWall = false; } } IEnumerator Dash() { isDashing = true; rb.velocity = new Vector2(dashSpeed * Mathf.Sign(rb.velocity.x), 0); dashTime = dashDuration; while (dashTime > 0) { dashTime -= Time.deltaTime; yield return null; } isDashing = false; } }