- Home /
Finding the forward vector of a child in local space?
What i'm trying to do is have a character move forward in the direction they are looking on a spaceship that is freely rotatable and will have any sort of orientation. I have the character moving in local space, and that keeps it glued to the floor, but the x and z component of the forward vector are different based on the ship's orientation. Here's my code:
Vector3 forward = head.transform.forward;
headHeading = new Vector3 (forward.x, 0, forward.z);
this.transform.localPosition += headHeading.normalized * walkSpeed;
I don't know whats actually happening, but i'm pretty sure it's because the forward vector is in world space, not local space. If i'm right about that, how do I make sure that the character does what is desired(moves in the direction the head is pointed whilst stuck to the ground, regardless of the ship's orientation)?
Here's an example: I have the ship in some crazy orientation.
I should be walking forwards but instead i'm drifting around,
In scene view, set tool handles to show local rotation (the button to the right of "Pivot"), and then click on each of the Ship, Player, and Head in turn. $$anonymous$$ake sure that their transforms are all oriented correctly so that their y axis (green) is pointing up, z (blue) is forward), and x (red) is right.
Answer by sweatyrat · Jul 15, 2015 at 06:57 PM
Vector3 forward = this.transform.parent.InverseTransformDirection(head.transform.forward);
headHeading = new Vector3 (forward.x, 0, forward.z);
this.transform.localPosition += headHeading.normalized * walkSpeed;
Answer by tanoshimi · Jan 11, 2015 at 08:16 AM
Your forward vector is in World Space, but that's what you want. A forward vector in local space would always be (0,0,1).
The problem might be your use of localPosition. What if you use position instead?
If not, you need to post more details of your hierarchy.
$$anonymous$$y hierarchy is: the Ship is the parent, the player character is a child of the ship and the head (camera) is a child to the character. Ship > Player > Head
I've tried using position ins$$anonymous$$d of localPosition but it doesn't fix the problem. Ins$$anonymous$$d, the character is moving up and down as well since the space is no longer relative to the floor of the ship. I think this is because the Y value of the vector needs to be 0 (since I want the player to stay on the floor).
Answer by Maurice_B · Jan 11, 2015 at 08:16 AM
could you use rotation instead?
transform.rotation.y = head.rotation.y;
tramform.Translate(0,0,walkspeed) ;