Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมตรวจสอบลูกบอล 3D จะชนกันได้หรือไม่ด้วย Acceleration ใน Python

ให้ลูกกลม 2 ลูก รัศมี r1,r2 ตำแหน่ง pos1,pos2 และ Acceleration acc1,acc2 ตรวจสอบว่าจะชนกันได้หรือไม่

ตัวอย่าง: r1=1,r2=2, pos1=(0,0,0), acc1=(100,0,0), pos2=(4,0,0), acc2=(0,0,0) → True

ขั้นตอน (Physics + Quadratic)

  1. Relative Position p = pos1-pos2, Relative Accel a = acc1-acc2
  2. ระยะทางยกกำลังสองเป็นฟังก์ชัน t: |p + 0.5*a*t²|²
  3. หา t ที่ minimize ระยะทาง (Vertex of Parabola)
  4. เช็คว่า min distance ≤ r1+r2

ตัวอย่างโค้ด

def solve(r1, r2, pos1, acc1, pos2, acc2):
    px, py, pz = pos1[0]-pos2[0], pos1[1]-pos2[1], pos1[2]-pos2[2]
    ax, ay, az = acc1[0]-acc2[0], acc1[1]-acc2[1], acc1[2]-acc2[2]
    da = ax*ax + ay*ay + az*az
    dp = px*px + py*py + pz*pz
    co = ax*px + ay*py + az*pz
    x = 0.0
    if da != 0:
        x = -co / da
    x = max(x, 0)
    dis = (da*x*x + 2*co*x + dp)**0.5
    return dis <= r1 + r2

r1, r2 = 1, 2
pos1 = (0, 0, 0)
acc1 = (100, 0, 0)
pos2 = (4, 0, 0)
acc2 = (0, 0, 0)
print(solve(r1, r2, pos1, acc1, pos2, acc2))  # Output: True

อินพุต

1, 2, (0, 0, 0), (100,0,0), (4, 0, 0), (0,0,0)

เอาต์พุต

True