Skip to content

Commit

Permalink
fix: adjust friction calculation [#1]
Browse files Browse the repository at this point in the history
  • Loading branch information
d3p1 committed Oct 13, 2024
1 parent efa8574 commit e88c3ab
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 14 deletions.
12 changes: 7 additions & 5 deletions docs/js/core/car.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ export default class Car {
centerY,
width,
height,
friction = 1,
force = 100,
friction = 50,
force = 200,
control = new Control(),
) {
this.centerX = centerX
Expand Down Expand Up @@ -144,12 +144,14 @@ export default class Car {
* until it reaches `0`. At that moment, the friction disappears
*/
#applyFriction(t) {
if (Math.abs(this.friction) > Math.abs(this.velocity)) {
const dragEffect = this.friction * t

if (dragEffect >= Math.abs(this.velocity)) {
this.velocity = 0
} else if (this.velocity > 0) {
this.velocity -= this.friction * t
this.velocity -= dragEffect
} else if (this.velocity < 0) {
this.velocity += this.friction * t
this.velocity += dragEffect
}
}

Expand Down
15 changes: 6 additions & 9 deletions docs/js/core/car/control.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export default class Control {
* @param {number} friction
* @param {number} torque
*/
constructor(friction = 0, torque = 20) {
constructor(friction = 5, torque = 20) {
this.friction = friction
this.torque = torque

Expand Down Expand Up @@ -91,12 +91,14 @@ export default class Control {
* until it reaches `0`. At that moment, the friction disappears
*/
#applyFriction(t) {
if (Math.abs(this.friction) > Math.abs(this.omega)) {
const dragEffect = this.friction * t

if (dragEffect >= Math.abs(this.omega)) {
this.omega = 0
} else if (this.omega > 0) {
this.omega -= this.friction * t
this.omega -= dragEffect
} else if (this.omega < 0) {
this.omega += this.friction * t
this.omega += dragEffect
}
}

Expand Down Expand Up @@ -174,9 +176,6 @@ export default class Control {
* Because `torque` is an angular force,
* and every force causes acceleration, then
* the `alpha`/angular acceleration is removed
* @todo For now, we are note going to use friction, and the
* `omega`/angular velocity will be reduce immediately to `0`
* without any force acting on it
*/
#addKeyUpListener() {
window.addEventListener('keyup', (e) => {
Expand All @@ -192,13 +191,11 @@ export default class Control {
case 'ArrowLeft':
this.left = false
this.alpha = 0
this.omega = 0
break

case 'ArrowRight':
this.right = false
this.alpha = 0
this.omega = 0
break
}
})
Expand Down

0 comments on commit e88c3ab

Please sign in to comment.