目录
向量¶
Vector 表示一个二维向量 (x, y)。我们的实现基于 Python 列表构建。
以下是构造 Vector 的一个示例:
>>> # Construct a point at 82,34 >>> v = Vector(82, 34) >>> v[0] 82 >>> v.x 82 >>> v[1] 34 >>> v.y 34 >>> # Construct by giving a list of 2 values >>> pos = (93, 45) >>> v = Vector(pos) >>> v[0] 93 >>> v.x 93 >>> v[1] 45 >>> v.y 45
优化使用方式¶
大多数情况下,你可以使用列表作为参数,而不必使用Vector。例如,如果你想计算两点之间的距离::
a = (10, 10)
b = (87, 34)
# optimized method
print('distance between a and b:', Vector(a).distance(b))
# non-optimized method
va = Vector(a)
vb = Vector(b)
print('distance between a and b:', va.distance(vb))
向量运算符¶
Vector 支持一些数值运算符,如 +、-、/:
>>> Vector(1, 1) + Vector(9, 5)
[10, 6]
>>> Vector(9, 5) - Vector(5, 5)
[4, 0]
>>> Vector(10, 10) / Vector(2., 4.)
[5.0, 2.5]
>>> Vector(10, 10) / 5.
[2.0, 2.0]
你也可以使用原地运算符:
>>> v = Vector(1, 1)
>>> v += 2
>>> v
[3, 3]
>>> v *= 5
[15, 15]
>>> v /= 2.
[7.5, 7.5]
- class kivy.vector.Vector(*largs)[源代码]¶
基类:
listVector 类。更多信息请参阅模块文档。
- angle(a)[源代码]¶
计算a和b之间的角度,并以度数返回该角度。
>>> Vector(100, 0).angle((0, 100)) -90.0 >>> Vector(87, 23).angle((-77, 10)) -157.7920283010705
- distance(to)[源代码]¶
返回两点之间的距离。
>>> Vector(10, 10).distance((5, 10)) 5. >>> a = (90, 33) >>> b = (76, 34) >>> Vector(a).distance(b) 14.035668847618199
- static in_bbox(point, a, b)[源代码]¶
如果 point 位于由 a 和 b 定义的边界框内,则返回 True。
>>> bmin = (0, 0) >>> bmax = (100, 100) >>> Vector.in_bbox((50, 50), bmin, bmax) True >>> Vector.in_bbox((647, -10), bmin, bmax) False
- length()[源代码]¶
返回向量的长度。
>>> Vector(10, 10).length() 14.142135623730951 >>> pos = (10, 10) >>> Vector(pos).length() 14.142135623730951
- length2()[源代码]¶
返回向量长度的平方。
>>> Vector(10, 10).length2() 200 >>> pos = (10, 10) >>> Vector(pos).length2() 200
- static line_intersection(v1, v2, v3, v4)[源代码]¶
找到直线(1)v1->v2与直线(2)v3->v4之间的交点,并将其作为向量对象返回。
>>> a = (98, 28) >>> b = (72, 33) >>> c = (10, -5) >>> d = (20, 88) >>> Vector.line_intersection(a, b, c, d) [15.25931928687196, 43.911669367909241]
警告
这是一个直线相交方法,而非线段相交。
- normalize()[源代码]¶
返回一个新的向量,其方向与vec相同,但长度为1。
>>> v = Vector(88, 33).normalize() >>> v [0.93632917756904444, 0.3511234415883917] >>> v.length() 1.0
- rotate(angle)[源代码]¶
使用角度(以度为单位)旋转向量。
>>> v = Vector(100, 0) >>> v.rotate(45) [70.71067811865476, 70.71067811865474]
- static segment_intersection(v1, v2, v3, v4)[源代码]¶
计算线段(1)v1->v2与(2)v3->v4之间的交点,并将其作为向量对象返回。
>>> a = (98, 28) >>> b = (72, 33) >>> c = (10, -5) >>> d = (20, 88) >>> Vector.segment_intersection(a, b, c, d) None
>>> a = (0, 0) >>> b = (10, 10) >>> c = (0, 10) >>> d = (10, 0) >>> Vector.segment_intersection(a, b, c, d) [5, 5]