📜 ⬆️ ⬇️

Simulation of the movement and drift of the machine in the game on JavaScript

It was necessary to write a game in javascript. I decided to stay on primitive races. When I mastered the principles of rotation and movement on HTML5 Canvas, the following problem appeared: driving. Making this game, I recalled the game Grand Prix Simulator 2 ZX Spectrum , in which I played on the computer "Byte".

The management there was the following:



It was easy to implement: the machine has a direction in radians; by pressing a button, it triggers the rotateLeft or rotateRight . These methods simply add or subtract the constant value of the change in angle from the direction of the machine.
')
But in that game the car was still skidding (at first uncomfortable, but more interesting with it). And I decided to write some drift emulation. In fact, a skid occurs when the machine itself changes direction, but its movement does not change direction with it. How accurate is it to reproduce motion from the point of view of physics? I set out to make such a drift, which will be similar to the real one.

First you need to separate the velocity vector and the direction of the car:

this.carDirection is the angle defining the orientation of the vehicle;
this.linearVelocity is the velocity vector specified in Cartesian coordinates.

Next, we hang the event changing the orientation of the car on the turn buttons. When it differs from the direction of the velocity vector, it begins to turn in the direction of the machine. The rate of rotation of this vector is given by the empirical coefficient SMOOTHING .



So, the car suffered. Tepr need to check whether the pilot was kept on the track. The route is a polyline, sections of which have a certain width. These lines on the track are at some angle. Thus, the task is formulated as follows: it is necessary to check whether a point falls into a rectangle located at some angle.
One of the ways will be the transfer of the coordinate system to the road section so that this road section lies on one of the axes. To do this, subtract the coordinates of the beginning of the segment from the coordinates of the machine, and then multiply them by the rotation matrix:

 function turnAndTranslate(lineIndex, position) { return [ trace[lineIndex].cos * (position[0] - trace[lineIndex].begin[0]) + trace[lineIndex].sin * (position[1] - trace[lineIndex].begin[1]), trace[lineIndex].sin * (- position[0] + trace[lineIndex].begin[0]) + trace[lineIndex].cos * (position[1] - trace[lineIndex].begin[1]) ]; } 


For the rotation matrix, multiply the coordinate vector by the matrix, which contains the sine and cosine of the rotation angle. In order not to calculate trigonometric functions for each test, they are calculated only once during the initialization of the map and are stored as coefficients for each segment of the route.



The program is damp, but you can already go here .

Source: https://habr.com/ru/post/164609/


All Articles