- Home /
Set the speed of an object by its distance with another object
Hi everyone !
The title may not be clear so let me explain what I want.
I'm making a four players game, with a single camera. My camera is following a path of points I made in the editor and I want to set its speed so that it always stays right behind the last player. Players are in a corridor so they won't ever go too far left or right.
What I want is : to calculate the distance between each player and the camera, take the lower distance and set the speed with it.
The problem is I only want to know the distance player/camera on the forward axis of the camera, like this :
If I use Vector3.Distance() it'll say that P4 is closer than P2. But on the Z axis of my cam P2 is closer. That's what I want.
I tried to do it with some Cos like this :
Vector3 v3_dirToPlayer = v3_playerPos - transform.Position;
float f_angleToPlayer = Vector3.Angle (transform.forward, v3_dirToPlayer);
float f_distToPlayer = Mathf.Cos (f_angleToPlayer) * Vector3.Distance (v3_playerPos, transform.Position);
But it didn't work well. The speed was good as the player kept moving forward but when moving left or right the speed went negative and really too far under 0 for no reason at all.
I'm asking for help. If someone has an idea please let me know.
Thanks !
Answer by robertbu · Mar 20, 2014 at 02:52 AM
A solution is to transform the four point into points local to the camera. You can use Transform.InverseTransformPoint(). Then you can just look at the 'z' distance to the point. For example, say you transform for p1:
Vector3 p1_local = transform.InverseTransformPoint(p1.position);
Now the 'z' value of 'p1_local' will be relative to the camera both in terms of position and direction. If p1 was at the same position as the camera, then v1_local would be (0,0,0). The 'z' value will be how far forward (or back) of the camera the points is in the coordinates of the camera.
Well... works great xD thanks ! I didn't really get the function of InverseTransformPoint. I tried to use it doing difference between player's localPos and cam localPos so it didn't work and I gave up on this...
Thanks, you helped me a lot !!