『小熊带你玩科技』KB代码实现3D赛车游戏?2kPlus Jam大赛了解一下,如何用2( 四 )


这里的道路俯仰角是使用「atan2」函数计算出来的 , 它被用于用于物理效果和照明 。
『小熊带你玩科技』KB代码实现3D赛车游戏?2kPlus Jam大赛了解一下,如何用2
文章图片
程序化的轨道生成器的示例结果 。
roadGenLengthMax=//endofsectionroadGenLength=//distanceleftroadGenTaper=//lengthoftaperroadGenFreqX=//XwavefrequencyroadGenFreqY=//YwavefrequencyroadGenScaleX=//XwaveamplituderoadGenScaleY=0;//YwaveamplituderoadGenWidth=roadWidth;//startingroadwidthstartRandSeed=randSeed=Date.now();//setrandomseedroad=[];//clearroad
//generatetheroadfor(i=0;i<roadEnd*2;++i)//buildroadpastend{if(roadGenLength++>roadGenLengthMax)//isendofsection?{//calculatedifficultypercentd=Math.min(1,i/maxDifficultySegment);//randomizeroadsettingsroadGenWidth=roadWidth*R(1-d*.7,3-2*d);//roadwidthroadGenFreqX=R(Lerp(d,.01,.02));//XcurvesroadGenFreqY=R(Lerp(d,.01,.03));//YbumpsroadGenScaleX=i>roadEnd?0:R(Lerp(d,.2,.6));//XscaleroadGenScaleY=R(Lerp(d,1e3,2e3));//Yscale//applytaperandmovebackroadGenTaper=R(99,1e3)|0;//randomtaperroadGenLengthMax=roadGenTaper+R(99,1e3);//randomlengthroadGenLength=0;//resetlengthi-=roadGenTaper;//subtracttaper}//makeawavyroadx=Math.sin(i*roadGenFreqX)*roadGenScaleX;y=Math.sin(i*roadGenFreqY)*roadGenScaleY;road[i]=road[i]?road[i]:{x:x,y:y,w:roadGenWidth};//applytaperfromlastsectionandlerpvaluesp=Clamp(roadGenLength/roadGenTaper,0,1);road[i].x=Lerp(p,road[i].x,x);road[i].y=Lerp(p,road[i].y,y);road[i].w=i>roadEnd?0:Lerp(p,road[i].w,roadGenWidth);//calculateroadpitchangleroad[i].a=road[i-1]?Math.atan2(road[i-1].y-road[i].y,segmentLength):0;}
开始游戏
现在轨道有了 , 剩下的启动过程就很简单了 。 我们只需要初始化几个变量 。
//reseteverythingvelocity=newVec3(pitchSpring=pitchSpringSpeed=pitchRoad=hueShift=0);position=newVec3(0,height);//setplayerstartposnextCheckPoint=checkPointDistance;//initnextcheckpointtime=maxTime;//setthestarttimeheading=randSeed;//randomworldheading
更新玩家状态
本节将介绍主要的更新函数 , 它可以处理游戏中所有内容的更新和渲染!通常 , 在代码写一个超大的函数并不是一个好习惯 , 我们需要将其分解成子函数 。 因此 , 为了方便理解 , 下面的叙述将其分为几部分 。
首先我们需要了解玩家所在位置的道路信息 。 为了使物理效果和渲染感觉平滑 , 在当前路段和下一个路段之间进行了插值操作 。
玩家的位置和速度是3D向量 , 并通过动力学进行更新以体现重力 , 阻尼和其他因素 。 如果玩家在道路下方 , 位置将被固定在地面上 , 并且速度会相对于法线反射 。 同样 , 在地面上时会施加加速度 , 并且越野行驶时相机会震动 。 经过游戏测试后 , 我决定允许玩家在空降时仍可以进行调整 。
在此处理输入以控制加速 , 刹车 , 跳跃和转弯 。 通过「mouseUpFrames」也可以检测到双击 。 有一些代码可以跟踪玩家在空中停留了多少帧 , 以便在玩家仍然可以跳跃的时候有一个短暂的宽限期 。
相机的俯仰角使用了一个简单的弹簧系统 , 在玩家加速、刹车和跳跃时给人一种动态的感觉 。 当玩家驾车翻越山丘以及跳跃时 , 摄像机也会根据道路角度倾斜 。
Update=()=>{
//getplayerroadsegments=position.z/segmentLength|0;//currentroadsegmentp=position.z/segmentLength%1;//percentalongsegment
//getlerpedvaluesbetweenlastandcurrentroadsegmentroadX=Lerp(p,road[s].x,road[s+1].x);roadY=Lerp(p,road[s].y,road[s+1].y)+height;roadA=Lerp(p,road[s].a,road[s+1].a);


推荐阅读