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

最终画出来的压痕
在这里插入图片描述

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值