using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Rigidbody2D rb;
public float speed;
public float jumpforce;
public Animator animator;
public Collider2D collider;
public bool isOnGroud;
public bool isInAir;
public LayerMask layer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
CheckIsOnHorizontalGround();
Movement();
}
private void Movement()
{
float horizonmentmove = Input.GetAxis("Horizontal");
float facedirection = Input.GetAxisRaw("Horizontal");
if (horizonmentmove != 0)
{
rb.velocity = new Vector2(horizonmentmove * speed, rb.velocity.y);
animator.SetFloat("running", Mathf.Abs(horizonmentmove));
}
//人物方向
if (facedirection != 0)
{
transform.localScale = new Vector2(facedirection, 1);
}
if (Input.GetButtonDown("Jump"))
{
rb.velocity = new Vector2(rb.velocity.x, jumpforce);
}
animator.SetFloat("falling", rb.velocity.y);
if (animator.GetBool("isInAir"))
{
animator.SetFloat("running", 0);
}
}
RaycastHit2D CreateOffsetRaycast(Vector2 offset,Vector2 rayDirection,float length,LayerMask layer)
{
// 获得玩家当前坐标位置
Vector2 playPos = transform.position;
// 生成玩家当前位置水平偏移的射线投射碰撞器
RaycastHit2D hit = Physics2D.Raycast(playPos + offset, rayDirection, length, layer);
// 如果于水平地面发生碰撞则显示红色,反之则显示绿色
Color rayColor = hit ? Color.red : Color.green;
// 在Scene中动态打印投射出的光线
Debug.DrawRay(playPos + offset, rayDirection * length, rayColor);
return hit;
}
public void CheckIsOnHorizontalGround()
{
// 生成玩家左侧检测射线
RaycastHit2D leftCheckRay = CreateOffsetRaycast(new Vector2(-0.5f, -1.125f), Vector2.down, 0.51f, layer);
// 生成玩家右侧检测射线
RaycastHit2D rightCheckRay = CreateOffsetRaycast(new Vector2(0.5f, -1.125f), Vector2.down, 0.51f, layer);
// 判断左右双射线是否与水平地面图层发生碰撞
if (leftCheckRay || rightCheckRay)
{
// 设置地面状态器为真
isInAir = false;
isOnGroud = true;
animator.SetBool("isOnGroud", true);
animator.SetBool("isInAir", false);
}
else
{
isInAir = true;
isOnGroud = false;
animator.SetBool("isOnGroud", false);
animator.SetBool("isInAir", true);
}
}
}
04-01
7292
05-25
3455
06-02