PVectors in Class Objects

I believe you didn’t grasp the reason I’ve advised you about cloning the passed PVector arguments inside __init__().

The idea is once we’ve got a clone of each passed object argument we don’t have to worry about inadvertently modifying them anymore.

Take a look at this sketch example based on yours:

class Foo:
    def __init__(self, targ_pos, mis_pos):
        self.targ_pos = targ_pos.get()
        self.mis_pos  = mis_pos.copy()


    def sub_vec(self):
        self.mis_pos.sub(self.targ_pos)
        return self


    def __str__(self, INFO = 'Foo { targ_pos: %s, mis_pos: %s }'):
        return INFO % (self.targ_pos, self.mis_pos)


targ_pos = PVector(100, 300, 0)
mis_pos = PVector(400, 600, 0)

foo = Foo(targ_pos, mis_pos)

def setup(FPS = .5): frameRate(FPS);

def draw(LOOPS = 4, INFO = 'Ori { targ_pos: %s, mis_pos: %s }\n'):
    background(int(random(PImage.ALPHA_MASK)))

    print foo.sub_vec()
    print INFO % (targ_pos, mis_pos)

    frameCount is LOOPS and noLoop()

And this is its log output:


Foo { targ_pos: [ 100.0, 300.0, 0.0 ], mis_pos: [ 300.0, 300.0, 0.0 ] }
Ori { targ_pos: [ 100.0, 300.0, 0.0 ], mis_pos: [ 400.0, 600.0, 0.0 ] }

Foo { targ_pos: [ 100.0, 300.0, 0.0 ], mis_pos: [ 200.0, 0.0, 0.0 ] }
Ori { targ_pos: [ 100.0, 300.0, 0.0 ], mis_pos: [ 400.0, 600.0, 0.0 ] }

Foo { targ_pos: [ 100.0, 300.0, 0.0 ], mis_pos: [ 100.0, -300.0, 0.0 ] }
Ori { targ_pos: [ 100.0, 300.0, 0.0 ], mis_pos: [ 400.0, 600.0, 0.0 ] }

Foo { targ_pos: [ 100.0, 300.0, 0.0 ], mis_pos: [ 0.0, -600.0, 0.0 ] }
Ori { targ_pos: [ 100.0, 300.0, 0.0 ], mis_pos: [ 400.0, 600.0, 0.0 ] }

Notice that even though property mis_pos is being mutated inside method sub_vec(): self.mis_pos.sub(self.targ_pos)

The original global mis_pos keeps its original initial value of: [ 400.0, 600.0, 0.0 ]

In short, both properties targ_pos & mis_pos can be mutated w/o modifying the original passed parameters, b/c the former are clones of the latter, via methods get() or copy():

def __init__(self, targ_pos, mis_pos):
    self.targ_pos = targ_pos.get()
    self.mis_pos  = mis_pos.copy()