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