Unity人物站跑跳运动转换

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);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值