[SOLVED] Adding multiple vectors together

I am trying to do the following ( something i used to do in unity) in playcanvas but it seems to not work at all.
I am trying to have an over the shoulder TPS camera that can see past the player forward.

I cant figure out how to add multiple vectors, and chaining them together seems to have no effect.

I’ve debugged and debugged and now im stuck.

So in a camera update loop, i want to adjust its position to always be offset from a target, and then add that vector to the players forward, right and up to always make sure its positioned correct to the player.

Code from unity = targetPos = cameraLookTarget.position + localPlauer.transform.forward * cameraOffset.z + localPlayer.transform.up * cameraOffset.y + localPlayer.transform.right * cameraOffset.x

Translates roughly to playcanvas

 var targetPosition = this.cameraLookTarget.getPosition().add(this.localPlayer.up.add(this.localPlayer.right.add(this.localPlayer.forward)));

Something to that effect but doesnt seem to do anything. any help is appreciated.

You need to create a new pc.Vec3 and do operations on that instead of chaining all those add calls like that. Basically when you access a vector it’s not a copy of the vector like in Unity - it’s the actual instance of the vector so you’re basically changing the properties themselves. So better do something like this (I haven’t tested this):

this.targetPosition = new pc.Vec3(); // do this in initialize or something so it's not done every frame
this.targetPosition.copy(this.cameraLookTarget.getPosition()).add(this.localPlayer.up).add(this.localPlayer.right).add(this.localPlayer.forward); // notice I'm not calling add() on the properties themselves but rather on the targetPosition field
1 Like

Be careful of using .add() as that modifies the Vec3 that you calling it from. It’s the equivalent of the doing +=

Another thing to be conscious of is that the Vector3 is a struct in Unity and Vec3 in PlayCanvas is an object.

This means that when you using the assignment operator in C#, if it’s a struct, it assigns by value. In Javascript, as it’s an object, it assigns by reference.

ie.
JS

var vec1 = new pc.Vec3();
var vec2 = new pc.Vec3();

vec1 = vec2;

// vec1 and vec2 are now referencing to the same instance of Vec3
2 Likes