views:

573

answers:

1

The code below projects the blue vector, AC, onto the red vector, AB, the resulting projected vector, AD, is drawn as purple. This is intended as my own implementation of this Wolfram demonstration.

Something is wrong however and I can really figure out what. Should be either that the projection formula itself is wrong or that I mistake some local coordinates with world coordinates. Any help is appreciated.

This code is trimmed but can still be executed without problems, assuming you have 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()
+5  A: 

Shouldn't this

D = project(AC,AB)
AD = vsub(D,A)

be

AD = project(AC,AB)
D = vadd(A,AD)

Unfortunately, I can't test it, but that's the only thing that looks wrong to me.

schnaader
Defining D by adding A to D doesnt work, since D isnt defined yet. Or am I missing something? Did you mean "D = vadd(A,AD)"?
mizipzor
Thanks, corrected.
schnaader
Tested it, and it seems to work. With that minor correction, I accept your answer, thanks. ;)
mizipzor