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