How to convert a direction Vector3 from world to local space
I am trying to make a custom 3rd person controller with Javascript.
I am getting float values from the axes of an analog stick (Xbox controller):
function Update() {
var moveX:float = Input.GetAxis("LeftStickX");
var moveY:float = Input.GetAxis("LeftStickY");
}
And I am using these floats to determine which direction my character needs to face:
function FixedUpdate() {
if(moveX || moveY){
var direction:Vector3 = new Vector3(moveX, 0, -moveY);
//direction = cam.transform.InverseTransformDirection(direction);
transform.forward = direction;
}
}
This works great, but only from one camera angle. Since "direction" is in the world space, it doesn't match up with whatever direction my camera may be facing.
If I can just convert "direction" from world space to the camera's local space, I should be able to control the character from many different camera angles.
Does anyone know how I can do this easily?
I tried using the commented-out line 4, which almost worked, except the x and z values of "direction" were reversed when my camera was facing east or west. ("cam" is the gameObject where my camera is stored)
i'm struggling with the same problem, did you find any solution ?
Answer by Winterblood · Feb 13, 2016 at 07:22 PM
Try this (not tested and I write in C# so I may have made typos!):
function FixedUpdate() {
if(moveX || moveY){
var direction:Vector3 = new Vector3(moveX, 0, -moveY); // Think of this as the dir in camera space
var t:Transform = cam.transform; // Make a local copy so we can change it
t.position = Vector3.zero; // We don't care about the position, only the orientation
direction = t * direction; // Transform dir into world space
direction.y = 0.0f; // Zero Y component so that facing is guaranteed to be horizontal even if camera is raised (unless directly overhead...but avoid that ;)
transform.forward = direction;
}
}
Your answer
Follow this Question
Related Questions
My character moves according to global Vectors 1 Answer
3rd person character controller rotation keeps resetting to 0 0 Answers
Object with fixed position but follows camera rotation 0 Answers
How to fix "the type or namespace ".." could not be found" in unity 0 Answers
3rd Person Movement / Camera Control Help or Advice Needed 1 Answer