1. 程式人生 > >unity中利用純物理工具製作角色移動跳躍功能

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