下面的代码将蓝色矢量AC投影到红色矢量AB上,得到的投影矢量AD绘制为紫色。这是我自己的this Wolfram demonstration实现。
然而,有些事情是错的,我可以真正弄清楚是什么。应该是投影公式本身是错误的,或者我错误地将一些局部坐标与世界坐标错误。任何帮助表示赞赏。此代码已修剪但仍可正常执行,假设您有pygame:
import pygame
from pygame.locals import *
def vadd(a,b):
return (a[0]+b[0],a[1]+b[1])
def vsub(a,b):
return (a[0]-b[0],a[1]-b[1])
def project(a, b):
""" project a onto b
formula: b(dot(a,b)/(|b|^2))
"""
abdot = (a[0]*b[0])+(a[1]*b[1])
blensq = (b[0]*b[0])+(b[1]*b[1])
temp = float(abdot)/float(blensq)
c = (b[0]*temp,b[1]*temp)
print a,b,abdot,blensq,temp,c
return c
pygame.init()
screen = pygame.display.set_mode((150, 150))
running = True
A = (75.0,75.0)
B = (100.0,50.0)
C = (90,70)
AB = vsub(B,A)
AC = vsub(C,A)
D = project(AC,AB)
AD = vsub(D,A)
while running:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
running = False
pygame.draw.line(screen, (255,0,0), A, B)
pygame.draw.line(screen, (0,0,255), A, C)
pygame.draw.line(screen, (255,0,255), A, D)
pygame.display.flip()
答案 0 :(得分:6)
不应该这个
D = project(AC,AB)
AD = vsub(D,A)
是
AD = project(AC,AB)
D = vadd(A,AD)
不幸的是,我无法测试它,但这是我唯一看错了。