- Home /
Rigidbody MovePosition based on the direction facing, but with x and z values calculated separately?
Currently, I'm doing an HTC Vive project, and the character which player control is moved by touching on the touch pad. Here is the specific line of code that controls how the character moves currently:
body.MovePosition (new Vector3 (body.position.x + vector.x * 3 * Time.deltaTime, body.position.y, body.position.z + vector.y * 3 * Time.deltaTime));
The vector.x and vector.y are the components of the coordinate which gets from the touch pad. They contain values ranged from -1 to 1, and they are used to control the direction and speed of the character's movement. However, I don't know how to add something like transform.forward in the formula to make the character's movement based on the direction it faced. So is it possible to add transform.forward or other direction to the formula like this? If yes, how can I change the formula?
Answer by Harinezumi · Mar 21, 2018 at 08:25 AM
You can either use Vector3.Scale()
on your transform.forward
(see example below), or you could try converting the touch vector into the world space direction defined by transform using Transform.TransformDirection(). Both approaches will require some tweaking (e.g. normalizing vectors).
// example 1:
Vector3 displacementDirection = transform.forward.Scale(new Vector3(vector.x, 0, vector.y)); // new vector needed because input coordinates are xy not xz
// example 2:
Vector3 displacementDIrection = transform.TransformDirection(new Vector3(vector.x, 0, vector.y));
So after calculating the displacementDirection, am I just need to change the code to this:
body.$$anonymous$$ovePosition (new Vector3 (body.position.x + displacementDirection.x * 3 * Time.deltaTime, body.position.y, body.position.z + displacementDirection.z * 3 * Time.deltaTime));
And it is okay? And what do you mean by requiring some tweaking?
Yes, that should work, but I would just use body.$$anonymous$$ovePosition(body.position + displacementDirection * 3 * Time.deltaTime);
. The y component should stay 0, but you can use Vector3.ProjectOnPlane(displacementDirection, Vector3.up)
to make sure.
By tweaking I mean for example what I wrote above, that you might need to project the displacement vector to not have y component, possibly even normalize it. Basically take into consideration small issues that can occur.
Btw, I would not use the constant 3 in the move, ins$$anonymous$$d declare a float moveSpeed
variable and use that. It will make the code more flexible and less prone to errors.
I see. It's working now! Thank you very much!