# Getting vectors, differencing vectors and comparing vectors. Certain pain.

Hello again Unity Community!

I have a problem, and a solution. My problem is that I need to be able to have a player prefab collide with a cube and for the cube to shoot off in one of four normalized directions. + X, -X or + Z and -Z. The cube, once hit on one of it’s for sides bullets off in that direction until it collides with another cube.

1. Get player’s Vector and the Cube’s Vector.
2. Minus one from another to get a Difference Vector.
3. Compare Absolute X to Absolute Z: The greater number is the Axis of movement.
4. IF axis is X, set X to 1 or -1. Set Z to 0
4b Vise versa for Z axis.
5. Set Y to 0
6. Multiply Vector by Speed and apply to Cube.

My JavaScript is somewhat very, very fresh. I have little experience but I can do the basics. I cannot wrap my head around this, no idea where to start, Sadly .

If someone from the community could explain to me how to go about this solution, and break it down (w/ commented code if possible).

It would be a life saving help. Thanks !!

(PS. Sorry if my posts are getting numerous and tiring ! )

Hey,

I haven’t read all your questions but don’t worry about it, that’s where the community is for!
My approach would be something like this:

1.Get the player’s direction(normalized)
2.multiply that direction with a speed (probably something like 90% of the player’s speed, just do what looks best)

To get the player’s direction, just save the lastPosition in a variable and then subtract that from it’s currentPosition. And simple just normalize that vector.

pseudo codo:

``````void onCollision(){
var direction = player.GetPreviousPos() - player.GetCurrentPos();
direction.normalize();

var speed=player.GetSpeed()*0.9;

}
``````

For the “player” and “cube” words, could I simply create variables using GameObject.Find to to reference the objects in the level ? Like so

``````function onCollision(){

var playerOne = GameObject.Find("PlayerOne") ;
var cubePush = GameObject.Find("CubePush") ;

var direction = playerOne.GetPreviousPos() - playerOne.GetCurrentPos();
direction.normalize();

var speed=playerOne.GetSpeed()*0.9;

}
``````

Although with this I get the “UnityException: You are not allowed to call this function when declaring a variable.”

Also a diagram I forgot, which may help matters.

It is pseudo code because I don’t know how your code is setup.
You will need to create the functions on the player (the GetPrevPos and GetCurrentPos).

Ah, how would I create those functions for the player ? Create a js called playerOne…

I am awefully lost. I wouldn’t know how to get the positions for the functions. This must be painful for coding vets to watch, surely.

Hey,

I think you should start with the basics. If you don’t know how scripting works, just follow some of the great tutorials Unity provided. In that way you will understand how scripting works.

http://unity3d.com/support/documentation/Manual/Scripting.html