Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class PlayerController : MonoBehaviour
- {
- [Header("Horizontal Movement Setting")]
- [SerializeField] private float walkSpeed = 1;
- [Header("Ground Check Setting")]
- [SerializeField] private Transform groundCheckPoint;
- [SerializeField] private float groundCheckY = 0.2f;
- [SerializeField] private float groundCheckX = 0.5f;
- [SerializeField] private LayerMask whatIsGround;
- [SerializeField] private float jumpForce = 45;
- private float xAxis;
- private Rigidbody2D rb;
- private bool isGrounded;
- private Animator anim;
- // Start is called once before the first execution of Update after the MonoBehaviour is created
- void Start()
- {
- rb = GetComponent<Rigidbody2D>();
- anim = GetComponent<Animator>();
- }
- // Update is called once per frame
- void Update()
- {
- GetInputs();
- Move();
- Jump();
- UpdateAnimations();
- }
- void GetInputs()
- {
- xAxis = Input.GetAxisRaw("Horizontal");
- }
- private void Move()
- {
- rb.linearVelocity = new Vector2(walkSpeed * xAxis, rb.linearVelocity.y);
- }
- private void Jump()
- {
- if (Input.GetButtonUp("Jump") && rb.linearVelocity.y > 0)
- {
- rb.linearVelocity = new Vector2(rb.linearVelocity.x, 0);
- }
- if (Input.GetButtonDown("Jump") && Grounded())
- {
- Debug.Log("Jump button pressed and player is grounded");
- rb.linearVelocity = new Vector3(rb.linearVelocity.x, jumpForce);
- }
- }
- private void UpdateAnimations()
- {
- anim.SetBool("Walking", rb.linearVelocity.x != 0 && Grounded());
- anim.SetBool("Jumping", !Grounded());
- }
- public bool Grounded()
- {
- bool groundCheck1 = Physics2D.Raycast(groundCheckPoint.position, Vector2.down, groundCheckY, whatIsGround);
- bool groundCheck2 = Physics2D.Raycast(groundCheckPoint.position + new Vector3(groundCheckX, 0, 0), Vector2.down, groundCheckY, whatIsGround);
- bool groundCheck3 = Physics2D.Raycast(groundCheckPoint.position + new Vector3(-groundCheckX, 0, 0), Vector2.down, groundCheckY, whatIsGround);
- return groundCheck1 || groundCheck2 || groundCheck3;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment