# 不懂物理的前端不是好的游戏开发者（一）—— 物理引擎基础

2021/08/19 18:05

### 代码中的数学

class Vector {
x: number
y: number
z: number
constructor(x: number,y: number,z: number) {
this.x = x
this.y = y
this.z = z
}

setX(x: number) {
this.x = x
}

setY(y: number) {
this.y = y
}

setZ(z: number) {
this.z = z
}
}


<center> <img src="https://img10.360buyimg.com/ling/jfs/t1/187655/26/15116/36501/60fe5e98E34fe5aa7/0ed9686b387c2d38.png" width=400> </img> <p>三角函数</p> </center>

class VectorOperation {
add (vectorA: Vector, vectorB: Vector) { //  向量相加
return new Vector(
vectorA.x + vectorB.x,
vectorA.y + vectorB.y,
vectorA.z + vectorB.z
)
}

minus (vectorA: Vector, vectorB: Vector) { // 向量相减
return new Vector(
vectorA.x - vectorB.x,
vectorA.y - vectorB.y,
vectorA.z - vectorB.z
)
}

multiply (vectorA: Vector, times: number) { // 向量缩放
return new Vector(
vectorA.x * times,
vectorA.y * times,
vectorA.z * times
)
}

dotProduct (vectorA: Vector, vectorB: Vector) { // 向量点积
return vectorA.x* vectorB.x + vectorA.y* vectorB.y + vectorA.z* vectorB.z
}

vectorProduct (vectorA: Vector, vectorB: Vector) { // 向量外积
return new Vector(
vectorA.y * vectorB.z - vectorA.z * vectorB.y,
vectorA.z * vectorB.x - vectorA.x * vectorB.z,
vectorA.x * vectorB.y - vectorA.y * vectorB.x,
)
}
}


<center> <img src="https://img11.360buyimg.com/ling/jfs/t1/185224/37/20023/79749/611cb271E555947b1/fb03f04909f34df0.png" width=400> </img> <p>微分的原理</p> </center>

### 物理基础

class GameObj {
pos: Vector
velocity: Vector
acceleration: Vector

constructor(pos?: Vector, velocity?: Vector, acceleration?: Vector) {
this.pos = pos || new Vector(0, 0, 0)
this.velocity = velocity || new Vector(0, 0, 0)
this.acceleration = acceleration || new Vector(0, 0, 0)
}

setPos (pos: Vector) {
this.pos = pos
}

setVelocity (velocity: Vector) {
this.velocity = velocity
}

setAcceleration (acceleration: Vector) {
this.acceleration = acceleration
}
}


$\vec F = m\vec a \tag{牛顿第二定律}$

class GameObj {
mess: number // 质量不得为 0

constructor(mess?: number) {
if (mess > 0) {
this.mess = mess
}
}

setMess (mess: number) {
if (mess > 0) {
this.mess = mess
}
}
}


class GameObj {
inverseMess: number // 质量不得为 0

constructor(inverseMess?: number) {
if (inverseMess >= 0) {
this.inverseMess = inverseMess
}
}

setInverseMess (inverseMess: number) {
if (inverseMess >= 0) {
this.inverseMess = inverseMess
}
}
}


0 评论
0 收藏
0