I have created basic movement for a drone using addRelativeForce with WASD input for movement in 4 directions and Spacebar to go up and leftcontrol to go down. I have added tilt when the quad moves. When i move in any of the 4 directions, because of the tilt the drone starts moving downward. I want the drone to ignore any rotation around x and z axis while adding force and only consider rotation around y axis because that will be used to rotate(swivel) my drone left and right.
Im using Vector3.up, Vector3.forward, Vector3.right with the addRelativeForce function along with appropriate multipliers that control the speed.
How do i approach this situation?
the relative force adds a force relative tothe rotation, so i got the negative of the object rotation for “fixing” the tilt direction. this code is assumming the helicopter is only tilted in one axis (tested in the x axis). i am not that good at vector maths so i cant think of a solution for all use cases. code example:
void Update () {
Vector3 vector = transform.forward;
GetComponent<Rigidbody>().AddRelativeForce(new Vector3(vector.x, -vector.y, vector.z));//thiss code asumes the object is rotated in the X axis.
}
AddRelavtive force, as the name suggests, applies your vector force relative to the Rigidbody’s directions. So when it is tilted, its forward, back.left.right directions will either be pointing up or down.
Try using AddForce or AddForceAtPosition instead.
@WarmedxMints but i need to consider rotation around y axis while moving as the quadcopter will be swivelling(rotating) around y axis when we move the mouse thats why im using addRelativeForce. So maybe as @xxmariofer suggested i should just add the z component of force and let the other 2 be zero. Then it will ignore the x and y component of the transform and move only in z direction.