場景圖
public class PlayerManage : MonoBehaviour
{
RaycastHit hitFoward, hitRight, hitLeft;
//射線長度膳凝,控制距離障礙物多遠(yuǎn)的時(shí)候開始觸發(fā)躲避
float rayLength;
//碰到障礙物時(shí)的反向作用力
Vector3 reverseForce;
//物體自身的速度
public Vector3 velocitySelf;
//判斷是否在進(jìn)行轉(zhuǎn)彎
bool IsTurn;
void Start()
{
rayLength = 2;
}
void Update()
{
Debug.DrawLine(transform.position, transform.position + transform.forward, Color.cyan);
Debug.DrawLine(transform.position, transform.position + (transform.forward + transform.right).normalized, Color.cyan);
Debug.DrawLine(transform.position, transform.position + (transform.forward - transform.right).normalized, Color.cyan);
if (Physics.Raycast(transform.position, transform.forward, out hitFoward, rayLength))
{
//Raycast.normal表示光線射到此表面時(shí),在此處的法線單位向量
reverseForce = hitFoward.normal * (rayLength - (hitFoward.point - transform.position).magnitude);
IsTurn = true;
}
if (Physics.Raycast(transform.position, transform.forward + transform.right, out hitFoward, rayLength))
{
reverseForce = hitFoward.normal * (rayLength - (hitFoward.point - transform.position).magnitude);
IsTurn = true;
}
if (Physics.Raycast(transform.position, transform.forward - transform.right, out hitFoward, rayLength))
{
reverseForce = hitFoward.normal * (rayLength - (hitFoward.point - transform.position).magnitude);
IsTurn = true;
}
if (!IsTurn)
{
reverseForce = Vector3.zero;
//通過這個(gè)控制當(dāng)物體躲避完障礙物以后速度變?yōu)樵瓉淼乃俣忍浚瑸榉乐刮矬w的速度越來越大
velocitySelf = velocitySelf.normalized * (new Vector3(3, 0, 3).magnitude);
}
velocitySelf += reverseForce;
transform.position += velocitySelf * Time.deltaTime;
if (velocitySelf.magnitude > 0.01)
{
//控制物體轉(zhuǎn)彎秒啦,讓物體的正前方和速度的方向保持一致
transform.forward = Vector3.Slerp(transform.forward, velocitySelf, Time.deltaTime);
}
IsTurn = false;
}
}
這里邊注意
這個(gè)就是獲取射線碰到墻時(shí)的那個(gè)法線方向,就是操縱力的方向鸥鹉,如下圖
通過滲透深度蛮穿,來判斷操縱力的大小