Let the object move in any direction
Implementation needs to be noted:
- Trigonometric function
- Sinusoidal
- Cosine
- Radian
- Computer programs use radians
- Avoid generating a large radian value
usingUnityengine;usingSystem.Collections;//Implement a box to move from the origin to the angular direction of each change (2.0f * mathf.pi)/10.0f//Move out of the screen and start the next move by the origin. Public classAnydirectionmotiontest:monobehaviour {//X position of Object floatPosX =0;//Y position of Object floatPosY =0;//Object Speed floatSpeed =3;//speed of the object in the x direction floatSpeedx;//speed of the object in the y direction floatSpeedY;//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;//Offset radians floatAngle =0;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;//Initial position (0,0) pointTransform.localposition =NewVector3 (PosX, PosY,0);//angle Default is 0 initial x minute speedSpeedx = speed * Mathf.cos (angle);//angle defaults to 0 initial y-point speedSpeedY = speed * Mathf.sin (angle); }voidUpdate () {//Detect, if the object is out of the interface, let it go back to the (0,0) point //And the degree of rotation plus (2.0f * mathf.pi)/10.0f if(posx-boxhalfwidth >= screenrighttoppos.x | | PosX + boxhalfwidth <= screenleftbottompos.x | | Posy-boxhalfwidth >= Screenrighttoppos.y | | PosY + boxhalfwidth <= screenleftbottompos.y) {//Return (0,0) pointPosX =0; PosY =0; Angle + = (2.0f* Mathf.pi)/10.0f;if(Angle > (2.0f* Mathf.pi)) {//After a week after the radian reset to avoid this value too large to produce accuracy problems //Control the arc of rotation is always in (theta >= 0 && Theta <= 2PI)Angle-=2.0f* MATHF.PI; }//x minute SpeedSpeedx = speed * Mathf.cos (angle);//y minute SpeedSpeedY = speed * Mathf.sin (angle); }//x direction of displacement to a value per frame of timePosX + = Speedx * TIME.DELTATIME;//y direction of displacement to a value per frame of timePosY + = SpeedY * TIME.DELTATIME;//Set the position of the box for this frameTransform.localposition =NewVector3 (PosX, PosY,0); }}
Unity game Development Math and Physics 3 (Let the object move in any direction)