前提
1、人物
2、添加box collider
3、添加Rigidbody
主要用Rigidbody来跳跃
1、设置跳跃力度
2、标记示范在地面,在地面才能跳跃
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour //继承
{
public float speed = 5f; //移动速度
private Rigidbody2D rb2d;//做一个Rb
public float jumpForce = 10.0f; // 跳跃力量的大小
public bool isGrounded = true; // 标记角色是否站在地面上
private Collider2D col;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
col = GetComponent<Collider2D>();
}
void Update()
{
Move();
if (isGrounded && Input.GetButtonDown("Jump")) //判断放在update里,当是地面且按下跳跃
{
// 应用向上的力来使角色跳跃
rb2d.velocity = Vector2.up * jumpForce;
isGrounded = false; // 标记角色已离开地面
}
}
void Move()
{
float horizontal = Input.GetAxis("Horizontal"); // WASD或箭头键的左右输入
float vertical = Input.GetAxis("Vertical"); // WASD或箭头键的上下输入
Vector3 movement = new Vector3(horizontal, 0, vertical) * speed * Time.deltaTime;
transform.Translate(movement); // 移动物体
}
private void OnCollisionEnter2D(Collision2D collision) //检查触碰地面方法
{
// 检查碰撞的对象是否是地面(这里假设地面有一个特定的标签,比如"Ground")
if (collision.gameObject.CompareTag("Ground")) //gameobject就是物体本身
{
isGrounded = true;
}
}
}