Archive for 23 5 月, 2019

2D/3D抛物线

23 5 月, 2019

#include<iostream>

using namespace std;
using uint=unsigned int;

struct vec2
{
float x,y;
};

struct vec3
{
float x,y,z;
};

/**
* 算出指定数量的抛物线高度值
* @param count 结果数量
* @param start 起始时间量,一般为-1
* @param end 结束时间量,一般为+1
*/
float *Parabolic(const uint count,const float time_start=-1,const float time_end=1)
{
if(count<=0)return(nullptr);

float *result=new float[count];

float rate;
float cur=time_start;
float total_time=time_end-time_start;

for(uint i=0;i<count;i++)
{
rate=float(i)/float(count);

cur=time_start+rate*total_time;

result[i]=1-cur*cur;

cout<<“height[“<<i<<“] “<<result[i]<<endl;
}

return result;
}

/**
* 画2D抛物线
* @param start 起始点
* @param end 结束点
* @param up 单位向上量
* @param height 高度值
* @param count 数量
*/
void Put2D(const vec2 &start,const vec2 &end,const vec2 &up,const float *height,const uint count)
{
vec2 total;
vec2 pos;
float rate;

total.x=end.x-start.x;
total.y=end.y-start.y;

cout<<“from “<<start.x<<“,”<<start.y<<” to “<<end.x<<“,”<<end.y<<endl;

for(uint i=0;i<count;i++)
{
rate=float(i)/float(count);

pos.x=start.x+rate*total.x;
pos.y=start.y+rate*total.y;

pos.x+=height[i]*up.x;
pos.y+=height[i]*up.y;

cout<<i<<“: “<<pos.x<<“,”<<pos.y<<endl;
}
}

/**
* 画3D抛物线
* @param start 起始点
* @param end 结束点
* @param up 单位向上量
* @param height 高度值
* @param count 数量
*/
void Put3D(const vec3 &start,const vec3 &end,const vec3 &up,const float *height,const uint count)
{
vec3 total;
vec3 pos;
float rate;

total.x=end.x-start.x;
total.y=end.y-start.y;
total.z=end.z-start.z;

cout<<“from “<<start.x<<“,”<<start.y<<“,”<<start.z<<” to “<<end.x<<“,”<<end.y<<“,”<<end.z<<endl;

for(uint i=0;i<count;i++)
{
rate=float(i)/float(count);

pos.x=start.x+rate*total.x;
pos.y=start.y+rate*total.y;
pos.z=start.z+rate*total.z;

pos.x+=height[i]*up.x;
pos.y+=height[i]*up.y;
pos.z+=height[i]*up.z;

cout<<i<<“: “<<pos.x<<“,”<<pos.y<<“,”<<pos.z<<endl;
}
}

void Test2D(float *height,const uint count)
{
vec2 start,end,up;

start.x=0;
start.y=0;

end.x=100;
end.y=0;

up.x=0;
up.y=100;

Put2D(start,end,up,height,count);
}

void Test3D(float *height,const uint count)
{
vec3 start,end,up;

start.x=0;
start.y=0;
start.z=0;

end.x=100;
end.y=0;
end.z=100;

up.x=0;
up.y=100;
up.z=0;

Put3D(start,end,up,height,count);
}

void main()
{
constexpr uint count=10;

float *height=Parabolic(count);

Test2D(height,count);
Test3D(height,count);

delete[] height;
}

鄂ICP备09027626号