Can someone explain the math behind finding the velocity relative to where I'm looking?
I want to use Dani's (a youtuber) script for my project, however, I want to understand his code so I can implement it on my own in future projects but there is one function that I don't understand. here it is:
public Vector2 FindVelRelativeToLook() {
float lookAngle = orientation.transform.eulerAngles.y;
float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
float u = Mathf.DeltaAngle(lookAngle, moveAngle);
float v = 90 - u;
float magnitue = rb.velocity.magnitude;
float yMag = magnitue * Mathf.Cos(u * Mathf.Deg2Rad);
float xMag = magnitue * Mathf.Cos(v * Mathf.Deg2Rad);
return new Vector2(xMag, yMag);
}
Answer by Captain_Pineapple · Mar 31, 2020 at 07:21 AM
There are a lot of videos and tutorials out there explaining the math behind it. This solution you got here is not really neat. And not really performant.
E.g. one could at least shorten the code:
public Vector2 FindVelRelativeToLook() {
// calculates the angle between your current look direction (orientation.transform.eulerAngles.y) and your velocity vector direction (Arcus tanges of x and y velocity)
float lookAngle = orientation.transform.eulerAngles.y;
float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
float u = Mathf.DeltaAngle(lookAngle, moveAngle);
float magnitude = rb.velocity.magnitude;
// apply the angle to your current velocity.
float yMag = magnitude * Mathf.Cos(u * Mathf.Deg2Rad);
float xMag = -magnitude * Mathf.Sin(u * Mathf.Deg2Rad);
return new Vector2(xMag, yMag);
}
it could also be done easier without calculating any angles by simply using vector projection.
Answer by romans8710 · Mar 31, 2020 at 09:04 AM
could you link me one of those videos please or tell me what this concept is called? @Captain_Pineapple
Your answer
Follow this Question
Related Questions
GameObject Jittering 0 Answers
In a scene with multiple doors if one is opened lock all of others? 1 Answer
Is there a Unity.Mathematics doing same thing than Vector3.SignedAngle 1 Answer
GameObject doesn't move 1 Answer
Rotate Vector3 1 Answer