資源簡介
實現了3D方塊動畫旋轉,自己也可以輸出角度來控制。
代碼片段和文件信息
import?math
import?matplotlib.pyplot?as?plt
import?matplotlib.animation?as?animation
class?Point3D:
????def?__init__(self?x?=?0?y?=?0?z?=?0):
????????self.x?self.y?self.z?=?x?y?z
?
????def?rotateX(self?angle):
????????“““?Rotates?this?point?around?the?X?axis?the?given?number?of?degrees.?“““
????????rad?=?angle?*?math.pi?/?180
????????cosa?=?math.cos(rad)
????????sina?=?math.sin(rad)
????????y?=?self.y?*?cosa?-?self.z?*?sina
????????z?=?self.y?*?sina?+?self.z?*?cosa
????????return?Point3D(self.x?y?z)
?
????def?rotateY(self?angle):
????????“““?Rotates?this?point?around?the?Y?axis?the?given?number?of?degrees.?“““
????????rad?=?angle?*?math.pi?/?180
????????cosa?=?math.cos(rad)
????????sina?=?math.sin(rad)
????????z?=?self.z?*?cosa?-?self.x?*?sina
????????x?=?self.z?*?sina?+?self.x?*?cosa
????????return?Point3D(x?self.y?z)
?
????def?rotateZ(self?angle):
????????“““?Rotates?this?point?around?the?Z?axis?the?given?number?of?degrees.?“““
????????rad?=?angle?*?math.pi?/?180
????????cosa?=?math.cos(rad)
????????sina?=?math.sin(rad)
????????x?=?self.x?*?cosa?-?self.y?*?sina
????????y?=?self.x?*?sina?+?self.y?*?cosa
????????return?Point3D(x?y?self.z)
?
????def?project(self?win_width?win_height?fov?viewer_distance):
????????“““?Transforms?this?3D?point?to?2D?using?a?perspective?projection.?“““
????????factor?=?fov?/?(viewer_distance?+?self.z)
????????x?=?self.x?*?factor?+?win_width?/?2
????????y?=?-self.y?*?factor?+?win_height?/?2
????????return?Point3D(x?y?self.z)
class?Simulation:
????def?__init__(
????????????self?
????????????width=128?
????????????height=160?
????????????fov=64?
????????????distance=4?
????????????rotateX=5?
????????????rotateY=5?
????????????rotateZ=5
????????????):
?
????????self.vertices?=?[
????????????Point3D(-11-1)
????????????Point3D(11-1)
????????????Point3D(1-1-1)
????????????Point3D(-1-1-1)
????????????Point3D(-111)
????????????Point3D(111)
????????????Point3D(1-11)
????????????Point3D(-1-11)
????????]
????????
????????#?Define?the?edges?the?numbers?are?indices?to?the?vertices?above.
????????self.edges??=?[
????????????#?Back
????????????(0?1)
????????????(1?2)
????????????(2?3)
????????????(3?0)
????????????#?Front
????????????(5?4)
????????????(4?7)
????????????(7?6)
????????????(6?5)
????????????#?Front-to-back
????????????(0?4)
????????????(1?5)
????????????(2?6)
????????????(3?7)
????
評論
共有 條評論