抛物线算法(已知起点、终点、高度)

(194) 2024-04-03 15:01:01

以下内容为转载内容,来自:http://tr4work.blog.163.com/blog/static/1371493142011329113733260/


不多说了,直接上算法:

首先我们要知道子弹的起点和终点,以及你想让子弹飞的高度。然后算出路径
CGPoint startPoint = CGPointMake(20,20);
CGPoint endPoint = CGPointMake(200,20);
int height = 100;
int x1 =  startPoint.x; //起始点
int y1 = startPoint.y;
int x3 =endPoint.x;//终点
int y3 = endPoint.y;
//发射路径宽度
int width = abs(x3 - x1);
//算出中间会经过的一点
int x2 = x1 + width/2;
int y2 = y1 - height;
//根据抛物线方程ax^2+bx+c=y,得方程组 //ax1^2+bx1+c=y1 //ax2^2+bx2+c=y2 //ax3^2+bx3+c=y3 //解方程组得抛物线的a,b,c

b = ((y1-y3)*(x1*x1-x2*x2)-(y1-y2)*(x1*x1-x3*x3))/((x1-x3)*(x1*x1-x2*x2)-(x1-x2)*(x1*x1-x3*x3)); 


a = ((y1-y2)-b*(x1-x2))/(x1*x1-x2*x2);


 c = y1-a*x1*x1-b*x1;

//x轴速度为vx

float vx = width/5;//5为秒

//算出新坐标

- (void)update:(ccTime)dt {

 CGPoint position = sprite.position;
           x = position.x + dt*vx;
           y = a*x^2 + b*x + c;
           sprite.position = ccp(x, y);


这是我用在cocos2d游戏中的一个抛物线路径算法,希望对大家有用

THE END

发表回复