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
- {
- public GameObject ground;
- private Rigidbody2D rb;
- private float directionValue;
- private float movementSpeed;
- private float jumpForce;
- private KeyCode jumpKey;
- private bool isGrounded;
- private bool tickJump;
- private void Awake()
- {
- ground = GameObject.Find("Ground");
- rb = gameObject.GetComponent<Rigidbody2D>();
- movementSpeed = 5;
- jumpForce = 350;
- jumpKey = KeyCode.Space;
- isGrounded = true;
- tickJump = false;
- }
- private void Update()
- {
- directionValue = Input.GetAxisRaw("Horizontal");
- if(directionValue != 0)
- {
- MoveCharacter();
- }
- if(Input.GetKeyDown(jumpKey) && isGrounded == true)
- {
- tickJump = true;
- }
- }
- private void FixedUpdate()
- {
- if (gameObject.GetComponent<BoxCollider2D>().IsTouching(ground.GetComponentInChildren<BoxCollider2D>()))
- {
- isGrounded = true;
- }
- else
- {
- isGrounded = false;
- }
- if(tickJump == true)
- {
- rb.AddForce(Vector2.up * jumpForce * Time.deltaTime, ForceMode2D.Impulse);
- tickJump = false;
- }
- }
- private void MoveCharacter()
- {
- Transform characterTransform = gameObject.transform;
- Vector3 newPosition = Vector3.zero;
- newPosition.Set(directionValue * movementSpeed, 0, 0);
- characterTransform.position += newPosition * Time.deltaTime;
- }
- private IEnumerator JumpEvent()
- {
- do
- {
- yield return null;
- }
- while (rb.velocity.y != 0 && isGrounded != true);
- isGrounded = true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement