2-5. 物理环境监测及绘制

物理环境监测代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PhysicsCheck : MonoBehaviour
{
    [Header("监测参数")]
    public Vector2 bottomOffset;
    public float checkRaduis;
    public LayerMask groundLayer;

    [Header("状态")]
    public bool isGround;

    void Update()
    {
        Check();
    }

    public void Check()
    {
        // 监测地面
        isGround = Physics2D.OverlapCircle((Vector2)transform.position + bottomOffset, checkRaduis, groundLayer);
    }

    private void OnDrawGizmosSelected()
    {
        // 绘制监测区
        Gizmos.DrawWireSphere((Vector2)transform.position + bottomOffset, checkRaduis);
    }
}

然后在 Jump 方法中判断,只有在地面上才能跳跃

    private void Jump(InputAction.CallbackContext context)
    {
        // Debug.Log("JUMP");
        if (physicsCheck.isGround)
        {
            // 只有在地面上才能进行跳跃

            // 这里使用的是 ForceMode2D.Impulse,表示瞬间修改人物上方向的速度为 jumpForce 对应的数值
            rb.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
        }
    }

最终结果如下图所示

项目相关代码

代码仓库:https://gitee.com/nbda1121440/2DAdventure.git

标签:20240224_0323

posted @   hellozjf  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示