Adding gravity to the motion of an object
Implementation NOTE:
usingUnityengine;usingSystem.Collections;//Adding gravity to the motion of the object Public classParabolicmotiontest:monobehaviour {//X position of Object floatPosX =0;//Y position of Object floatPosY =0;//speed of the object in the x direction floatSpeedx =0;//speed of the object in the y direction floatSpeedY =-8;//The top right pixel of the screen in world space coordinatesVector3 Screenrighttoppos;//The left lower pixel of the screen in world space coordinatesVector3 Screenleftbottompos;half width of//box floatBoxhalfwidth;//Run time floatRunTime;//Gravitational acceleration Const floatGR =0.4F//Where the object was bornVector2 Bornpos;voidStart () {//Convert the pixel on the right of the screen to the coordinates of world spaceScreenrighttoppos = Camera.main.ScreenToWorldPoint (NewVector3 (Screen.width, Screen.height,0));//Convert the pixel at the bottom right of the screen to the coordinates of world spaceScreenleftbottompos = Camera.main.ScreenToWorldPoint (NewVector3 (0,0,0));//box half width, because box is squareBoxhalfwidth = transform.localscale.x *0.5F//Birth location upper left cornerBornpos =NewVector2 (screenleftbottompos.x + boxhalfwidth, screenrighttoppos.y-boxhalfwidth);//Initial position screen upper left cornerTransform.localposition =NewVector3 (Bornpos.x, Bornpos.y,0); }voidUpdate () {//Detect, if the object is out of the interface, let it go back to the Bornpos point if(posx-boxhalfwidth >= screenrighttoppos.x | | PosX + boxhalfwidth <= screenleftbottompos.x | | Posy-boxhalfwidth >= Screenrighttoppos.y | | PosY + boxhalfwidth <= screenleftbottompos.y) {//upper left corner of the screenPosX = bornpos.x; PosY = Bornpos.y;//Run time 0RunTime =0; }//x direction of displacement to a value per frame of timePosX = Speedx * runTime;//y direction of displacement to a value per frame of timePosY = (0.5F * GR * Runtime * Runtime) + (SpeedY * runtime) + Bornpos.y;//Time change valueRunTime + = Time.deltatime;//Set the position of the frameTransform.localposition =NewVector3 (PosX, PosY,0); }}
Unity game Development Math and Physics 4 (adding gravity to Object motion)