- Home /
Get value -1 to 1 from direction between 2 points
So, this is somewhat of a loaded question and I will try to do my best to explain it.
I am creating a vehicle AI system, and the vehicle has a Steer(x) function. X ranges from -1(steer left) to 1(steer right).
I'm trying to find the value that I need to pass to that function to steer my vehicle accordingly to a target, in this case the next checkpoint.
An example: Imagine a vehicle to the right of a checkpoint, this function should return something like -0.2 to steer the vehicle back towards the checkpoint.
This is what i've tried:
Vector3 relativePos = path.corners[0] - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(relativePos);
float y = transform.eulerAngles.y;
float DeltaAngle = Mathf.DeltaAngle(y, targetRotation.eulerAngles.y);
Debug.Log(DeltaAngle / 360f);
and
float dot = Vector3.Dot(transform.forward.normalized, (_Target.position - transform.position).normalized);
However it doesn't produce the correct steering value.
Any help would be appreciated.
It's hard to judge what would work not knowing the project, but the dot product approach should work. You would want to take the dot product with a different direction though, otherwise you'll get incorrect angles;
//Use transform.right because we want a value of 1 when the target is to the right, and a value of -1 when the target is to the left
//This is already normalized, so we don't need to normalize it again
float dot = Vector3.Dot (transform.right, (_Target.position - transform.position).normalized);
Answer by Bunny83 · Jul 13, 2019 at 09:53 AM
It should be
float dot = Vector3.Dot(transform.right, (_Target.position - transform.position).normalized);
Keep in mind that the value would get smaller rather quick as closer you get to the right direction. So you would never actually reach the target direction. You could use a quadratic fall off. For this you would need to seperate the direction (sign) from the magnitude.
float dir = Mathf.Sign(dot);
float mag = Mathf.Abs(dot);
mag = Mathf.Pow(1f - mag, 2);
float steer = dir * (1f - mag);
Instead of 2 you could use a larger value to make the fall off more narrow around the target direction.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
(Scripting) Getting a circle of points in an array 1 Answer
Random Gaussian Generator 0 Answers