我想将图像从上到下移动到Bézier曲线路径上,但是我无法得到如何从此路径计算x / y点和斜率.路径如下图所示:
我有起点,终点和两个控制点.
Path path = new Path(); Point s = new Point(150,5); Point cp1 = new Point(140,125); Point cp2 = new Point(145,150); Point e = new Point(200,250); path.moveTo(s.x,s.y); path.cubicTo(cp1.x,cp1.y,cp2.x,cp2.y,e.x,e.y);
解决方法
这是一个立方Bézier曲线,其公式简单地为[x,y] =(1-t)^ 3 * P0 3(1-t)^ 2 * t * P1 3(1-t)t ^ 2 * P2吨^ 3 * P3.有了这个,您可以通过评估方程来求解每个点.在Java中,您可以这样做:
/* t is time(value of 0.0f-1.0f; 0 is the start 1 is the end) */ Point CalculateBezierPoint(float t,Point s,Point c1,Point c2,Point e) { float u = 1 – t; float tt = t*t; float uu = u*u; float uuu = uu * u; float ttt = tt * t; Point p = new Point(s.x * uuu,s.y * uuu); p.x += 3 * uu * t * c1.x; p.y += 3 * uu * t * c1.y; p.x += 3 * u * tt * c2.x; p.y += 3 * u * tt * c2.y; p.x += ttt * e.x; p.y += ttt * e.y; return p; }
所以,如果你想沿着路径移动一个精灵,那么你可以根据你想要的路径有多远,来设置t值从0到1的值.例:
int percentMovedPerFrame = 1;// Will complete path in 100 frames int currentPercent = 0; update() { if (currentPercent < 100) { this.pos = CalculateBezierPoint(currentPercent / 100.0f,this.path.s,this.path.c1,this.path.c2,this.path.e); currentPercent += percentMovedPerFrame } }