- Home /
The question is answered, right answer was accepted
How does GetRelativeVector work?
I found some code online for a simple 2D car movement script. However, I want to understand WHY it works the way it does so I can make tweaks to it. I'm particularly confused with 'GetRelativeVector':
float direction = Vector2.Dot(rb.velocity, rb.GetRelativeVector(Vector2.up));
if(direction >= 0.0f) {
rb.rotation += h * steering * (rb.velocity.magnitude / 5.0f);
//rb.AddTorque((h * steering) * (rb.velocity.magnitude / 10.0f));
} else {
rb.rotation -= h * steering * (rb.velocity.magnitude / 5.0f);
//rb.AddTorque((-h * steering) * (rb.velocity.magnitude / 10.0f));
(where 'rb' is an instance of Rigidbody2D). Here's what the manual says: As far as I can tell, Vector2.up is just synonymous to a simple vector (0,1). And this vector is the 'local space vector' argument. So what would rb.GetRelativeVector(Vector2.up) be?
Answer by Owen-Reynolds · Jan 04, 2020 at 01:35 AM
That exact equation rb.GetRelativeVector(Vector2.up)
looks like it's simply getting the [EDITS: xxforwardxx -- opps, UP] unit vector. [xxIt turns out there's no easier way to get thatxx]. rb.rotation is a special 0-360 float. It seems to work independently of rb.transform. An easy shortcut to spin rigibbodies (I don't know 2D -- not sure why regular 2D sprites have to use a 3D rotation).
All rb.GetRelativeVector does is spin the input by -rotation degrees. If rotation is 90, it turns (5,0) into (0,5).
Ok, gotcha! I'm not sure why this was giving me so much trouble. Another question, though: would I be able to replace rb.GetRelativeVector(Vector2.up) with just transform.up? What is the difference between the 'transform' and the Rigidbody2D variable 'rb'? Aren't they one and the same?
I think yes: rb.transform.up is the same as that longer way, sort of. It's a Vector3 with z always 0, which means it acts like a Vector2 (assigning v2=rb.transform.up is safe).
There's one tiny issue: if you manually change rb.rotation (ins$$anonymous$$d of letting physics do it), there's a 1-frame lag until transform.rotation.z catches up (which is very weird). So if other parts of code may change it, the long way is probably safer to exa$$anonymous$$e the actual up vector.
Follow this Question
Related Questions
Rb2D.MovePosition not working - weird error... 1 Answer
Push an Object with a vector created from two points. 0 Answers
CharacterControllers and Transform.Rotate 1 Answer
Raycast 2D 0 Answers
Character won't move (Fixed) 1 Answer