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 Movement : MonoBehaviour
- {
- [Header("Movement")]
- public float speed;
- Rigidbody2D body;
- Vector2 mov;
- public bool FacingRight = true;
- public bool canMov = true;
- [Header("Jump")]
- public float jumpForce;
- public bool grounded = false;
- public Transform groundCheck;
- private float nextJump = 0.5f;
- public float extraJump = 0;
- [Header("Input")]
- float moveHorizontal;
- [Header("Animation")]
- Animator anim;
- void Start()
- {
- body = GetComponent<Rigidbody2D>();
- anim = GetComponent<Animator>();
- }
- // Update is called once per frame
- void Update()
- {
- if (canMov)
- {
- moveHorizontal = Input.GetAxis("Horizontal");
- grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
- Debug.DrawLine(transform.position, groundCheck.position, Color.green);
- if (Input.GetButtonDown("Jump") && grounded)
- {
- if (Time.time > nextJump)
- {
- nextJump = Time.time + 0.5f;
- StartCoroutine(Jump());
- }
- }
- if (Input.GetButton("Jump") && !grounded)
- {
- extraJump += Time.deltaTime * jumpForce * 50;
- }
- else
- {
- extraJump = 0;
- }
- }
- }
- void FixedUpdate()
- {
- if (canMov)
- {
- Move();
- }
- }
- void Move()
- {
- mov = new Vector2(moveHorizontal * speed, body.velocity.y);
- body.velocity = mov;
- //FacingParameters
- if (moveHorizontal > 0 && !FacingRight)
- {
- Flip();
- }
- else if (moveHorizontal < 0 && FacingRight)
- {
- Flip();
- }
- //AnimParameters
- if (moveHorizontal != 0)
- AnimHorizontal();
- }
- IEnumerator Jump()
- {
- body.AddForce(new Vector2(0, jumpForce),ForceMode2D.Impulse);
- float elapsedTime = 0;
- while (elapsedTime < 0.18f)
- {
- elapsedTime += Time.deltaTime;
- body.AddForce(new Vector2(0, extraJump), ForceMode2D.Force);
- yield return new WaitForSeconds(0);
- }
- }
- public void Flip()
- {
- FacingRight = !FacingRight;
- Vector3 X_Scale = transform.localScale;
- X_Scale.x *= -1;
- transform.localScale = X_Scale;
- }
- void AnimHorizontal()
- {
- anim.SetFloat("Walk", Mathf.Abs(moveHorizontal));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement