unity实现人物跳跃 学习笔记(2)

目录

1、设置地面

2、设置刚体(重力)

3、脚本代码


1、设置地面

选择地面新建图层为ground

新建一个empty在player内部

 

 

 

 圆心设置在人物脚底

将组件拖动到脚本transform上 

脚本地面选择ground图层

 

 

 

2、设置刚体(重力)

重力设置为10

半径0.5

跳跃力18

 

 

3、脚本代码
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Tilemaps;
using UnityEngine;

public class move : MonoBehaviour
{
    // Start is called before the first frame update
    public float speed;
    Rigidbody2D rb;
    bool facingRight = true;
    bool isGrounded;//判断是否在地上
    public Transform groundCheck;//用来判断是否落地的组件,会向外做一个判断圆圈,地面在圆圈内则视为落地
    public float checkRadius;//判断圆圈的半径
    public LayerMask whatIsGround;//地面的图层,通常是layermask的别名

    public float jumpForce;//跳跃力
    void filp() {
        
        transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
        facingRight = !facingRight;
    }

    
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        
    }

    // Update is called once per frame
    void Update()
    {

        float input = Input.GetAxisRaw("Horizontal");
        if (input > 0 && facingRight == false)
        {
            filp();
        }
        else if (input < 0 && facingRight == true)
        {
            filp();
        }
        rb.velocity = new Vector2(input * speed, rb.velocity.y);
//用来判断是否在地上的代码
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
//设置跳跃的代码,落地由重力控制
        if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded == true)
        {
            rb.velocity = Vector2.up * jumpForce;
        }
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值