七.角色控制

1.基本控制

新建脚本文件夹scripts

添加脚本PlayerController.cs

添加到player上

在这里插入图片描述

public float moveSpeed; //移动速度
public Rigidbody2D theRB;   //刚体

设置刚体为player

void Update()
{
    //设置速度
    theRB.velocity = new Vector2(moveSpeed * Input.GetAxis("Horizontal"), theRB.velocity.y);
}

查看Input设置
在这里插入图片描述

public float jumpForce; //跳跃力量

//Update()中加入
//跳跃
if(Input.GetButtonDown("Jump"))
{
    theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
}

在这里插入图片描述

在这里插入图片描述

落地时,穿透地面,需设置

在这里插入图片描述

碰撞不光滑,在墙边角跳跃效果不佳。

新建物理材质
在这里插入图片描述

设置摩擦为0

在这里插入图片描述

拖到player下的Collider2D中Material下

在这里插入图片描述

2.跳跃控制

添加层级

在这里插入图片描述

在这里插入图片描述

设置地面层级为Ground, player层级为Player

在这里插入图片描述

private bool isGrounded;    //是否在地面
public Transform groundCheckPoint;  //地面检测点
public LayerMask whatIsGround;      //地面层级

在player上新建空对象GroundPoint
在这里插入图片描述

设置空对象位置

在这里插入图片描述

设置地面位置点
在这里插入图片描述

//检测是否在地面
isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, .2f, whatIsGround);

//跳跃
if (Input.GetButtonDown("Jump"))
{
  if(isGrounded)  //判断是否在地面
  {
    theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
  }
}

3.连跳

//连跳
private bool canDoubleJump; //是否能连跳


void Update()
{
    //设置速度 /*GetAxisRaw*/
    theRB.velocity = new Vector2(moveSpeed * Input.GetAxis("Horizontal"), theRB.velocity.y);

    //是否在地面
    isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, .2f, whatIsGround);

    if (isGrounded)
    {
        //在地面时,可以连跳为true
        canDoubleJump = true;
    }

    //跳跃
    if (Input.GetButtonDown("Jump"))
    {
        if(isGrounded)  //是否在地面
        {
            theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
        }
        else
        {
            if(canDoubleJump)
            {
                //不在地面,连跳
                theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
                canDoubleJump = false;
            }
        }
    }
}
  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值