Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class CharacterController2D : MonoBehaviour
- {
- private Rigidbody2D rb;
- public LayerMask groundLayer;
- private float directionValue;
- private float movementSpeed;
- private float jumpForce;
- private KeyCode jumpKey;
- private bool isGrounded;
- private bool tickJump;
- private void Awake()
- {
- rb = gameObject.GetComponent<Rigidbody2D>();
- groundLayer = LayerMask.GetMask("Ground");
- movementSpeed = 500;
- jumpForce = 350;
- jumpKey = KeyCode.Space;
- isGrounded = true;
- tickJump = false;
- }
- private void Update()
- {
- directionValue = Input.GetAxisRaw("Horizontal");
- if(Input.GetKeyDown(jumpKey) && isGrounded == true)
- {
- tickJump = true;
- StartCoroutine(JumpEvent());
- }
- }
- private void FixedUpdate()
- {
- RaycastHit2D hit0 = Physics2D.Raycast(transform.position, Vector2.down, 0.55f, groundLayer);
- RaycastHit2D hit1 = Physics2D.Raycast(transform.position + new Vector3(-0.5f, 0, 0), Vector2.down, 0.55f, groundLayer);
- RaycastHit2D hit2 = Physics2D.Raycast(transform.position + new Vector3(0.5f, 0, 0), Vector2.down, 0.55f, groundLayer);
- isGrounded = hit0.collider != null || hit1.collider != null || hit2.collider != null;
- if (tickJump == true)
- {
- rb.AddForce(Vector2.up * jumpForce * Time.deltaTime, ForceMode2D.Impulse);
- tickJump = false;
- }
- rb.velocity = new Vector2(directionValue * movementSpeed * Time.deltaTime, rb.velocity.y);
- }
- private IEnumerator JumpEvent()
- {
- do
- {
- yield return null;
- }
- while (isGrounded != true);
- isGrounded = true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement