https://blog.51cto.com/u_15273495/5040568

在游戏开发中,有时你可能希望不使用物理引擎来实现一些物理效果。可以通过手动编写代码来模拟这些效果,以下是一些常见方法和示例代码:

1. 运动学公式

使用基本的运动学公式来模拟物体的运动。假设你有一个物体,它的初始位置、速度和加速度是已知的,你可以使用以下公式来计算它的新位置和速度:

  • 位置更新公式:
    position = position + velocity * deltaTime + 0.5 * acceleration * deltaTime^2
  • 速度更新公式:
    velocity = velocity + acceleration * deltaTime\

2.手动检测碰撞

https://blog.csdn.net/yhn19951008/article/details/119899092

通过编写代码来检测物体之间的碰撞。以下是一个简单的 AABB (Axis-Aligned Bounding Box) 碰撞检测示例:

1
2
3
4
bool IsColliding(Rect a, Rect b)
{
return a.xMin < b.xMax && a.xMax > b.xMin && a.yMin < b.yMax && a.yMax > b.yMin;
}

3. 模拟重力

https://blog.csdn.net/dcs147/article/details/68063421

手动添加重力效果,可以通过每帧更新物体的速度和位置来实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Vector3 position;
Vector3 velocity;
Vector3 acceleration = new Vector3(0, -9.81f, 0); // 重力加速度

void Update()
{
float deltaTime = Time.deltaTime;

// 更新速度
velocity += acceleration * deltaTime;

// 更新位置
position += velocity * deltaTime;

// 将位置应用到物体
transform.position = position;
}

4. 阻尼效果

添加阻尼效果来模拟摩擦力或空气阻力:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
float damping = 0.98f; // 阻尼系数

void Update()
{
float deltaTime = Time.deltaTime;

// 更新速度并应用阻尼
velocity += acceleration * deltaTime;
velocity *= damping;

// 更新位置
position += velocity * deltaTime;

// 将位置应用到物体
transform.position = position;
}

5. 碰撞响应

手动处理碰撞响应,例如在碰撞时反弹:

1
2
3
4
5
void OnCollisionEnter(Collision collision)
{
Vector3 normal = collision.contacts[0].normal;
velocity = Vector3.Reflect(velocity, normal);
}

6. 简单力学模拟

手动应用力和转矩:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Vector3 force;
Vector3 torque;

void ApplyForce(Vector3 newForce)
{
force += newForce;
}

void ApplyTorque(Vector3 newTorque)
{
torque += newTorque;
}

void Update()
{
float deltaTime = Time.deltaTime;

// 更新速度和位置
velocity += (force / mass) * deltaTime;
position += velocity * deltaTime;

// 更新角速度和角度
angularVelocity += (torque / inertia) * deltaTime;
angle += angularVelocity * deltaTime;

// 重置力和转矩
force = Vector3.zero;
torque = Vector3.zero;

// 将位置和旋转应用到物体
transform.position = position;
transform.rotation = Quaternion.Euler(0, 0, angle);
}

通过这些方法,你可以在不使用物理引擎的情况下实现一些简单的物理效果。根据实际需求,可以组合使用这些技术来模拟更复杂的物理行为。