using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class PlayerController : MonoBehaviour
{
private float movementInputDirection;//检测玩家是否进行任何输入--玩家尝试移动的方向
private Rigidbody2D rb;
private int amountOfJumpsLeft;//还剩下多少跳跃次数
private Animator anim;//为获取附加到玩家的动画组件而定义
private bool isFacingRight = true;//希望角色移动时会面对速度方向
private bool isWalking;
private bool isGrounded;
private bool canJump;
public float movementSpeed=10.0f;
public int amountOfJumps;//设置能跳多少次
public float jumpForce = 16.0f;//为跳跃设置向上的速度
public Transform groundCheck;//用于检查是否着地的变量
public float groundCheckRadius;
public LayerMask whatIsGround;
void Start()
{
rb.GetComponent<Rigidbody2D>();//获取挂载此脚本对象的Rigidbody2D组件。
anim.GetComponent<Animator>();//获取挂载此脚本对象的Animator组件。
amountOfJumpsLeft = amountOfJumps;
}
private void CheckMoveMentDirection()
{
if (isFacingRight && movementInputDirection < 0)
{
Flip();
}
else if
(!isFacingRight && movementInputDirection > 0)
{
Flip();
}
if (rb.velocity.x != 0)
{
isWalking = true;
}
else
{
isWalking = false;
}
}
private void UpdateAnimations()
{
anim.SetBool("isWalking", isWalking);//设置玩家Animator参数中的isWalking的值
anim.SetBool("isGrounded", isGrounded);
anim.SetFloat("yVelocity", rb.velocity.y);
}
private void CheckInput()//检测玩家是否进行任何输入
{
movementInputDirection = Input.GetAxisRaw("Horizontal");//玩家按A返回-1,按D返回1
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
void Update()
{
CheckInput();
CheckMoveMentDirection();
UpdateAnimations();
CheckIfCanJump();
}
private void CheckIfCanJump()
{
if(isGrounded&&rb.velocity.y <= 0)
{
amountOfJumpsLeft = amountOfJumps;
}
if (amountOfJumpsLeft <= 0)
{
canJump = true;
}
else
{
canJump = false;
}
}
private void FixUpdate()
{
ApplyMovement();
CheckSurroundings();
}
private void CheckSurroundings()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);//检查whatIsGround图层中的碰撞物体是否与圆形区域重合。
}
private void CheckInput()
{
rb.velocity = new Vector2
(movementSpeed * movementInputDirection, rb.velocity.y);
//直接设置角色刚体的速度
}
private void Flip()//让玩家转向
{
isFacingRight = !isFacingRight;
transform.Rotate(0.0f, 180.0f, 0.0f);
}
private void ApplyMovement()
{
rb.velocity = new Vector2(movementSpeed * movementInputDirection, rb.velocity.y);
}
private void Jump()
{
if(canJump)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
amountOfJumpsLeft--;
}
}
private void OnDrawGizmos()
{
Gizmos DrawWireSphere(groundCheck.position, groundCheckRadius);//绘制一个用于检测碰撞的球体。
}
}