Right now I'm trying to make the player cube move left, right, up and down in relation to the camera's rotation and position. I figured what I could do is create an empty game object, make the main camera the parent, and then get the vector pointing from the camera's child to another game object that follows the cube's exact position, and that would give me the direction the cube should roll towards.
I have my example in profile view, but in 3D view the camera should be facing the cube with the cube at the center.
So I have the following line of code code:
Vector3 forwardVector = (position1.transform.position - position2.transform.position).normalized;
If you look at the image on the right hand side, I Debug.GetLine'd the resulting vector from the cube's position and ended up with a vector pointing down. In theory though, it should be pushing off to the right hand side. Here's the rest of the code:
Vector3 perpendicularVector = Vector3.Cross (Vector3.up, resultant).normalized;
if (Input.GetKey (KeyCode.UpArrow))
{
cube.rigidbody.AddForce ( forwardVector * moveSpeed);
}
if (Input.GetKey(KeyCode.DownArrow))
{
cube.rigidbody.AddForce ( forwardVector * -moveSpeed);
}
if (Input.GetKey (KeyCode.LeftArrow))
{
cube.rigidbody.AddForce ( perpendicularVector * -moveSpeed);
}
if (Input.GetKey (KeyCode.RightArrow))
{
cube.rigidbody.AddForce ( perpendicularVector * moveSpeed);
}
As a result, when I press the up arrow key, I end up with the cube flying upwards toward the sky, and the down key brings it back down towards the plane, but my intention is for the vector to move along the XZ plane.
Also, with this line of code, I was hoping to get the line perpendicular to my intended vector and Vector3.up, but I naturally get wonky results from that.
Vector3 perpendicularVector = Vector3.Cross (Vector3.up, resultant).normalized;
If there's an easier method to achieving my goals, that's fine, but it would be nice too to figure out why the vector is pointing down instead of to the right.
It's also might be worth noting that the camera already successfully rotates around the player cube.