玩家控制脚本(优化)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
// [SerializeField] ------写在private前,使私有界面可视化
private Rigidbody2D rb;
private Animator anim;
public float speed;
public float jumpforce;
[Space]
public LayerMask ground;//获取地面信息
public Collider2D coll;
[Space]
public int Cherry;
public Text CherryNum;
private bool isHurt;//默认是false
public AudioSource boom,JumpAudio,CollectionAudio,HurtAudio;
public GameObject Death;
public Collider2D DisColl;
public Transform CeilingCheck;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();//获取Component组件
anim = GetComponent<Animator>();
}
// Update is called once per frame
//根据每一秒的实际帧数来平滑动画效果---兼容其他电脑
void FixedUpdate()
{
if(!isHurt)
{
Movement();
}
SwitchAnim();
}
void Movement()
{
//GetAxis --- 获得 -1到1 这三个数字包括其中所有的小数
float horizontalmove = Input.GetAxis("Horizontal");
//GetAxisRwo --- 直接获得 -1 0 1 这三个数字
float facedircetion = Input.GetAxisRaw("Horizontal");
//当正在移动时
if(horizontalmove != 0)
{
//获得速度的变化 ↓方向*速度 ↓使效果更平滑 ↓没有跳跃所以y轴没有变化
rb.velocity = new Vector2(horizontalmove * speed * Time.fixedDeltaTime, rb.velocity.y);
//实现idle和run动画效果切换 ↓-用数学函数[绝对值]保证永远>0
anim.SetFloat("running",Mathf.Abs(horizontalmove));
}
//判断角色面向方向
if(facedircetion !=0)
{
//获取transform下的scale ↓输入的方向 yz轴不变
transform.localScale = new Vector3(facedircetion,1,1);
}