Here is my code.
I am trying to extract a single component (Vector3.x) from a Vector3 as a float
g_TCnewpos = Vector4;
g_MC = new Vector4[n];
cForce = Vector3;
var simpleVec4Distance = g_TCnewpos - g_MC[0];
var g_squaredVector = simpleVec4Distance.sqrMagnitude;
// OK so far...
// but then:
cForce.x = (1 / g_squaredVector.x) * g_MC[0].w * g_MC[1].w;
cForce.y = (1 / g_squaredVector.y) * g_MC[0].w * g_MC[1].w;
cForce.z = (1 / g_squaredVector.z) * g_MC[0].w * g_MC[1].w;
generates these ERRORS:
test.js(11,7): BCE0019: 'x' is not a member of 'float'.
test.js(12,7): BCE0019: 'y' is not a member of 'float'.
test.js(13,7): BCE0019: 'z' is not a member of 'float'.
It’s still not really clear what exactly you want to calculate. As i understand your description you want each component of your Vector3 to be squared and then you want to take the inverse of each component and form a new vector? That sounds really strange to me. What’s the purpose of this? It has some similarities with the formula for gravity, however if that’s your goal you’re way off.
Anyways to square each component of a vector independently from each other you can use the Scale method to scale your vector with itself.
Now your g_squaredVector would have each component squared (== new Vector4(xx, yy, zz, ww)).
ps: Your array of Vector4 looks like it should represent a matrix. Unity has the Matrix4x4 type which has all common operators you can do with a 4x4 matrix.
Again, it would help if you would explain your actual problem you want to solve.
edit
Since it looks like you want to calculate the force in an electric field, here’s what you have to do. I guess your g_MC array contains your charges of your electric field and each vector is made of a Vector3 that represents the position of a charge and the 4th (w) coordinate is it’s charge?
// ...
float k = 8.987551787368e9f; // Coulomb's constant
Vector3 force = Vector3.zero;
foreach(var C in g_MC)
{
Vector3 dir = (Vector3)(g_TCnewpos - C); // only the vector
force += dir.normalized * C.w / dir.sqrMagnitude;
}
force *= k;
Keep in mind that this calculates the force applied to a unit-charge (like in the definition of the electric field). If your “g_TCnewpos” represents a test charge that can have a different charge than 1 you should also multiply by “g_TCnewpos.w”. Like this:
force += dir.normalized * g_TCnewpos.w * C.w / dir.sqrMagnitude;
That’s it. Of course if you want to calculate the force for simulation purposes you might need to adjust Coulomb’s constant or multiply by some scaling factor.
EDIT It is a best practice in my opinion to change the whole Vector3 at once, instead of each value individually. That should make it slightly faster, as well as ensuring that they don’t get edited wrong. If you need to, change the g_squaredVector variable to separate variables to reflect that you wanted each one to be either x, y or z, and hold the correct value.