简体   繁体   中英

Player rotating along wrong axis?

I have a character that is essentially a sphere, but scaled at y1, x1.2, z1 (a spheroid).

I can apply force to the object in any given 'pushDirection', which is a product of the character's rigidbody position minus the main camera transform position (this works fine to move the character in the direction the camera is facing – 'forwards' in my game should always be in the direction the camera is facing).

But now I'm trying to make the object rotate forwards – in the direction the camera is facing – instead of adding force. I'm adding torque instead. [Here's a rough illustrated screenshot of my goal with my intended axis:

Note that whenever the camera rotates around the object, the axis for rotation will shift.

Instead though, I'm getting a result where the character rotates as is shown in this illustrated screenshot:

As mentioned, as the camera moves the axis for rotation shifts along with the camera. But I want the object to move away from the camera rather than rotate to the left. (Note, in both screenshots I had the object suspended without gravity to try and debug its rotation).

Relevant bits of my script are below:

 void Start () { rb = GetComponent<Rigidbody>(); pushForward = rb.transform.position - Camera.main.transform.position; } void Update() { speed = rb.velocity.magnitude; pushForward = rb.transform.position - Camera.main.transform.position; if (Input.GetKey("w")) { isForward = true; } else { isForward = false; } } void FixedUpdate () { // IF KEY IS DOWN, MOVE // if (isForward == true) { float turn = Input.GetAxis("Vertical"); rb.AddTorque(pushForward * torque * turn); Debug.Log("Moving Forward"); } } 

I've played around with this so much I just can't get my head around it. I'm also totally confused as if I change the Input.GetAxis to "Horizontal", the debug message "Moving Forward" pops up fine but I don't get any sort of rotation in the object – none at all.

If anyone could point me in the right direction I'd really appreciate it, i've gotten myself a bit confused.

If I understood you correctly, in order to obtain the rotation you want, you need to cross multiply pushForward with Vector3.down .

IE:

void FixedUpdate() {
    // IF KEY IS DOWN, MOVE //
    if (isForward == true) {
        var vect = Vector3.Cross(pushForward, Vector3.down);
        float turn = Input.GetAxis("Vertical");
        rb.AddTorque(vect * torque * turn);
        Debug.Log("Moving Forward");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM