Unity TrailRenderer 画出轮胎压痕

需求:
在车拐弯的时候出现轮胎压痕。

压痕出现条件:
①.轮胎触碰到地板
②.轮胎角度有偏移
③.轮胎在转动


胎痕是断续的,所以每一段胎痕是单独的一个TrailRenderer
轮胎的转动跟角度可以通过wheelCollider来判断
轮胎触碰地板可以通过WheelCollider或者用射线的方式进行判断

压痕组件:

public class TireIndentation : MonoBehaviour
{
  Vehicles car;
  WheelCollider wheel;
  int index;
  public TrailRenderer render;
}  

通过射线检测轮胎是否着地

  bool IsDrawIndentation(out Vector3 indentationPos)
  {
    if (wheel == null)
    {
      indentationPos = Vector3.zero;
      return false;
    }
    Vector3 pos = wheel.transform.position;
    Ray ray = new Ray(pos, Vector3.down);
    RaycastHit hit;
    bool isHit = Physics.Raycast(ray, out hit, wheel.radius + 0.1f, GlobalValue.GroundLayer);
    if (isHit)
    {
      Debug.DrawLine(hit.point, pos);
      indentationPos = hit.point;
      //indentationPos
    }
    else indentationPos = Vector3.zero;
    return isHit;
  }

通过移动TrailRenderer来绘制压痕

  public void OnDrawIndentation()
  {
    Vector3 pos;
    bool isDraw = IsDrawIndentation(out pos);
    if (isDraw)
      render.transform.position = pos;
    else
    {
      OnBreakIndentation();
    }
  }

断开压痕

  public void OnBreakIndentation()
  {
    wheel = null;
    if(car != null) car.indentationComp[index] = null;
    this.transform.parent = null;
  }

外部调用:

//绘制
  virtual protected void ShowIndentationComp()
  {
    CreateIndentationComp();
    for(int i = 0;i < 2; i++)
    {
      indentationComp[i].OnDrawIndentation();
    }
  }

//创建一段新的压痕
  virtual protected void CreateIndentationComp()
  {
    for(int i = 0;i < 2; i++)
    {
      if (indentationComp[i]) continue;
      TireIndentation indentation = 
        TireIndentation.CreateIndentation(i, wheelColliders[i + 2], this);
      indentationComp[i] = indentation;
    }
  }

//是否绘制
  virtual protected bool IsShowIndentation()
  {
    if (!isPlayer) return false;

    Vector3 euler = this.transform.eulerAngles;
    if (euler.y > 180) euler.y -= 360;
    if (Mathf.Abs(euler.y) > GlobalValue.turnSideMaxAngle / 3)
      return true;
    else
      return false;
  }

//每帧执行
  public void Update()
  {
    if (IsShowIndentation())
      ShowIndentationComp();
    else
    {
      for(int i= 0; i < 2; i++)
      {
        if (indentationComp[i] == null) continue;
        else indentationComp[i].OnBreakIndentation();
      }
    }
  }

最终画出来的压痕
Unity TrailRenderer 画出轮胎压痕_第1张图片

你可能感兴趣的:(android,unity)