[Unity] changes the vector direction without changing its size.
Recently, when I was playing a brick-and-mortar game, I encountered a small problem, that is, the ball may perform round-robin between the left and right sides of the boundary, resulting in the game being unable to continue, so I want to change the direction of the ball when it hits the boundary vertically, but the speed remains unchanged. I tried some methods but did not achieve the effect. Later I thought that the speed is a vector, and the problem becomes to change the direction of a vector without changing its size. Google found the revolving matrix Wiki page.
Multiply the original vector matrix [x, y] by the rotation matrix
/// <Summary> // rotate the vector to change its direction, the size remains unchanged /// </summary> /// <param name = "v"> angle of rotation of the vector to be rotated </param> /// <param name = "angle"> </param> // <returns> the Rotated Vector </returns> private Vector2 RotationMatrix (Vector2 v, float angle) {var x = v. x; var y = v. y; var sin = Math. sin (Math. PI * angle/180); var cos = Math. cos (Math. PI * angle/180); var newX = x * cos + y * sin; var newY = x *-sin + y * cos; return new Vector2 (float) newX, (float) newY );}