参考:Unity 贝塞尔曲线实现抛物线运动,投掷功能实现
用到了DOTween插件, 回想起之前不知道这个插件还在用协程和SmoothDamp做运动控制的自己仿佛是个哈批
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class Test : MonoBehaviour
{
private Vector3 _startPoint = new Vector3(0, 0, 0);//设置原点为起点
private float _lineHeight;//抛物线高度
public GameObject 炮弹预制体;//抛射物体模型
private GameObject _bullet;
public LineRenderer lineRender;
private bool _moveFinish = true;
void Start()
{
_bullet = Instantiate(炮弹预制体);
_bullet.SetActive(false);
}
void Update()
{
//从摄像机发出到鼠标位置方向的射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
LayerMask mask = 1 << (LayerMask.NameToLayer("Floor"));//射线只检测"Floor"图层
if (Physics.Raycast(ray, out hit,Mathf.Infinity,mask.value))
{
GameObject gameobj = hit.collider.gameObject;
float Dis = Vector3.Distance(_startPoint, hit.point);
_lineHeight = Dis/2;//随距离变化曲率
/*绘制抛物线*/
var bezierControlPoint = (_startPoint + hit.point) * 0.5f+(Vector3.up*_lineHeight);
int resolution = 50;//曲线上的路径点数量,值越大,取得的路径点越多,曲线越平滑
var _path = new Vector3[resolution];
for (int i = 0; i < resolution; i++)
{
var t = (i+1) / (float)resolution;//归化到0~1范围
_path[i] = GetBezierPoint(t,_startPoint,bezierControlPoint,hit.point);//使用贝塞尔曲线的公式取得t时的路径点
}
lineRender.positionCount = _path.Length;
lineRender.SetPositions(_path);
if(Input.GetMouseButtonDown(0))
{
if (_moveFinish)
{
_bullet.transform.position = _startPoint;
_bullet.SetActive(true);
_bullet.transform.DOPath(_path, 1f).SetEase(Ease.OutSine).OnComplete(MoveCallback);
_moveFinish = false;
}
}
}
}
void MoveCallback()
{
_moveFinish = true;
}
/// <param name="t">0到1的值,0获取曲线的起点,1获得曲线的终点</param>
/// <param name="start">曲线的起始位置</param>
/// <param name="center">决定曲线形状的控制点</param>
/// <param name="end">曲线的终点</param>
public static Vector3 GetBezierPoint(float t, Vector3 start, Vector3 center, Vector3 end)
{
return (1 - t) * (1 - t) * start + 2 * t * (1 - t) * center + t * t * end;
}
}
路径绘制使用的LineRenderer文章来源:https://www.toymoban.com/news/detail-646842.html
文章来源地址https://www.toymoban.com/news/detail-646842.html
到了这里,关于Unity3D_物体抛物线运动的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!