unity中利用纯物理工具制作角色移动跳跃功能

时间:2023-03-08 17:05:39
unity中利用纯物理工具制作角色移动跳跃功能

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {

protected ContactFilter2D contactFilter;
protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16];
protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D>(16);
protected Rigidbody2D rigid2D;
protected Vector2 move;
public float minGroundNormalY = 0.6f;
public bool grounded = false;
//public float jumpForce=20f;
public float jumpSpeed = 5f;
public float horizonForce = 30f;
public Vector2 maxSpeed;

// Use this for initialization
void Start () {
rigid2D = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update () {

//实现跳跃的三种方案
//01,直接添加一个向上的力
//if (grounded && Input.GetKeyDown(KeyCode.Space)) rigid2D.AddForce(Vector2.up * jumpForce);
//02,直接添加一个向上的速度
//if (grounded && Input.GetKeyDown(KeyCode.Space)) rigid2D.velocity=(Vector2.up * jumpSpeed)+Vector2.right*rigid2D.velocity.x;
//03,蓄力实现不同的跳跃高度,这里需要设置跳跃按钮的增量速度
float j = Input.GetAxis("Jump");
if (grounded && (Input.GetButtonUp("Jump")||j>0.99f)) rigid2D.velocity = (Vector2.up * jumpSpeed*j) + Vector2.right * rigid2D.velocity.x;

if ((Mathf.Abs(Input.GetAxis("Horizontal")) > 0.01) && (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))) rigid2D.AddForce(Vector2.right * Mathf.Sign(Input.GetAxis("Horizontal")) * horizonForce);
//设置角色减速
if (grounded && !(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) || Input.GetKeyDown(KeyCode.Space))) rigid2D.drag = 20f;
else rigid2D.drag = 0f;

}

private void FixedUpdate()
{
grounded = false;
CheckGround();
if (Mathf.Abs(rigid2D.velocity.x) > maxSpeed.x) rigid2D.velocity = new Vector2(Mathf.Sign(rigid2D.velocity.x) * maxSpeed.x, rigid2D.velocity.y);
}

//判断是正站在某个物体上
void CheckGround()
{
move = Vector2.down;
int count = rigid2D.Cast(move, contactFilter, hitBuffer, 0.02f);//对碰撞体向下的方向检测是否站在某个物体上,精度由检测的射线数和射线长度决定
hitBufferList.Clear();
for (int i = 0; i < count; i++)
{
hitBufferList.Add(hitBuffer[i]);
}
//如果有一个 射线的碰撞点的法线的y大于minGroundNormalY那么设置grounded为true表示站在了物体上
//这里minGroundNormalY一般设置为1到0.6之间即可决定站的平面的倾斜度
for (int i = 0; i < hitBufferList.Count; i++)
{
Vector2 currentNormal = hitBufferList[i].normal;
if (currentNormal.y > minGroundNormalY)
{
grounded = true;
}
}
}
}