前言
- 项目中需要在彩虹发生爆炸的时候,发出射线到这些和彩虹交换位置棋子相同颜色的所有物体。
- 一开始的项目中使用的是直线。但是很单调,我改成了曲线。
效果
思路
- 因为使用的插件LeanTween自带曲线的API,会在给予的四个点间生成移动路径。
- 这四个点分别是startPoint,controlOne,controlTwo,endPoint
- 所以难点在于其中两个控制点的计算上。
- 我在通过LeanTween的TweenEditor观察几次过后发现,当两个控制点处于对称情况下的时候,刚好能够得到我想要的图形效果。
- - 因为项目中开始点和结束点都是完全随机的,所以两点之间的距离完全不是固定的,所以如果想要在所有的点之间生成相同的曲线形状,需要计算出一个比例值
- 上图就是我的数据,Control0的x值就是距离开始点的值,相比于整个开始点与结束点间距离的比例是10/3 = 3,而y值就是 2/3 =0.6
- 因此我们在计算的时候只需要动态的调整这两个参数就可以调整曲线的弯曲程度
代码生成
private static LTBezierPath GetCurvePath(Vector2 from, Vector2 to)
{
float dir = -1;
Vector3 fromPos = Common.getPiecePosition((int)from.x,(int)from.y);
Vector3 toPos = Common.getPiecePosition((int)to.x, (int)to.y);
float rateY = 0.3f;
float rateX = 3;
float xRadius = Vector3.Distance(fromPos, toPos) / rateX;
float yRadius = xRadius * rateY;
Vector3 controlPoint1 = Vector3.zero, controlPoint2 = Vector3.zero;
if (from.x == to.x)
{
if (to.y > from.y)
{
controlPoint1 = new Vector3(fromPos.x - yRadius, fromPos.y + xRadius, 0);
controlPoint2 = new Vector3(toPos.x - yRadius, toPos.y - xRadius, 0);
}
else if (to.y < from.y)
{
controlPoint1 = new Vector3(fromPos.x + yRadius, fromPos.y - xRadius, 0);
controlPoint2 = new Vector3(toPos.x + yRadius, toPos.y + xRadius, 0);
}
}
else if (from.y == to.y)
{
if (to.x > from.x)
{
controlPoint1 = new Vector3(fromPos.x + xRadius, fromPos.y + yRadius, 0);
controlPoint2 = new Vector3(toPos.x - xRadius, toPos.y + yRadius, 0);
}
else if (to.x < from.x)
{
controlPoint1 = new Vector3(fromPos.x - xRadius, fromPos.y - yRadius, 0);
controlPoint2 = new Vector3(toPos.x + xRadius, toPos.y - yRadius, 0);
}
}
else
{
float y = (to.y - from.y);
float x = (to.x - from.x);
float z = Mathf.Sqrt(x * x + y * y);
float xOffset = xRadius * (x / z);
float yOffset = xRadius * (y / z);
//按照斜率方向在直线上取距离From一定距离的点
Vector3 pointOne = new Vector3(fromPos.x + xOffset, fromPos.y + yOffset, 0);
//与他垂直的线
//根据这个来区分方向
float y2 = x;
float x2 = -y;
float xOffset2 = yRadius * (x2 / z);
float yOffset2 = yRadius * (y2 / z);
controlPoint1 = new Vector3(pointOne.x + xOffset2, pointOne.y + yOffset2, 0);
Vector3 pointTwo = new Vector3(toPos.x - xOffset, toPos.y - yOffset, 0);
controlPoint2 = new Vector3(pointTwo.x + xOffset2, pointTwo.y + yOffset2, 0);
}
return new LTBezierPath(new Vector3[] { fromPos, controlPoint2, controlPoint1, toPos });
}
拓展
- 通过更改曲线的扭曲方向,可以生成逆时针,蝴蝶的效果。你们自己拓展了。