Understanding Movement with Trigonometry in Programming: A Practical Approach
110 likes | 251 Vues
In this lesson, we explore the basics of movement in a 2D space using trigonometry. While moving left, right, up, and down is straightforward, diagonal movement introduces complexity. We delve into the properties of right triangles, including side relationships and angle measurements. Learn how to calculate horizontal (x) and vertical (y) displacements using sine and cosine functions. We'll also discuss radians and how to convert between degrees and radians for accurate calculations in programming. This foundational knowledge is crucial for game development and simulations.
Understanding Movement with Trigonometry in Programming: A Practical Approach
E N D
Presentation Transcript
Lesson 2 By us
Movement • moving left/right/up/down is easy • so are rotations • but if the goal is to move diagonally, there is a problem • the solution is trigonometry
The Right Triangle • every triangle has 3 sides • the sum of internal angles is 180 degrees • a2 + b2 = c2 c b a
Trig • let ‘x’ be an angle • sin(x) = opposite / hypotenuse • cos(x) = adjacent / hypotenuse • tan(x) = opposite / adjacent • you will never use “tan” in programming • “sin” and “cos” are crucial
Trig 2 • sin(z) = opposite / hypotenuse • cos(z) = adjacent / hypotenuse • tan(z) = opposite / adjacent
Trig 3 the scenario: • you have the angle (this._rotation) • you have the hypotenuse (speed) • now you need vertical length and horizontal length
Trig 4 Math.sin (z) = y / velocity y = Math.sin (z) * velocity Math.cos (z) = x / velocity x = Math.cos (z) * velocity
Trig 5 • so now that you have ‘x’ (horizontal displacement) • you also have ‘y’ (vertical displacement) ie: this._x += Math.cos (z) * velocity; this._y -= Math.sin (z) * velocity;
WAIT A MINUTE • the input for Math.sin () or Math.cos () is in radians • 1 radian = PI / 180 degrees • 1 degree = 180 / PI radians • to get PI, you type: Math.PI
More Radians example: z = z*Math.PI/180; //or z *= Math.PI/180; this._x += Math.cos (z) * velocity; this._y -= Math.sin (z) * velocity;