搭建场景
绿色长方形为地表,红色圆形为玩家
地表挂载碰撞组件
玩家挂载钢体组件和碰撞组件
将Collision Detection设置为Continuous,Constraints勾选Freeze Rotation Z;
在Player上创建名为MoveandJump的C#脚本
代码实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveandJump : MonoBehaviour
{
private Rigidbody2D rb;
private Collider2D coli;
public float speed, jumpForce;//移动速度,跳跃高度
public Transform groundCheck;//地面检测,判断Player是否落地
public LayerMask ground;//与那一次层级进行检测
public bool isGround;//是否在地面的状态,true则在地面,false这在空中
bool jumpPreesed;//将Update中的玩家输入和在FixedUpdate的跳跃方法连接起来
int jumpCount;//跳跃次数
void Start()
{
rb = GetComponent<Rigidbody2D>();
coli = GetComponent<Collider2D>();
}
void Update()
{
if (Input.GetButtonDown("Jump") && jumpCount > 0)
{
jumpPreesed = true;
}
}
void FixedUpdate()
{
//以groundCheck的位置为圆心,半径为0.1的圆进行检测,判断ground Layer是否在圆内
isGround = Physics2D.OverlapCircle(groundCheck.position, 0.1f, ground);
GroundMovement();
Jump();
}
//移动
void GroundMovement()
{
float horizontalMove = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(horizontalMove * speed, rb.velocity.y);
}
//跳跃
void Jump()
{
//落回地面恢复跳跃次数
if (isGround)
{
jumpCount = 2;
}
//第一次跳跃
if (jumpPreesed && isGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpCount--;//跳跃次数-1
jumpPreesed = false;//跳跃代码已执行完毕
}
//连跳
else if (jumpPreesed && jumpCount >0 && !isGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpCount--;
jumpPreesed = false;
}
}
}