4.3
Hey so is there anyway I can use the apply_force function in relative to a objects rotation. My game is 3D and third-person. Like how in a first person game WASD works in relative to the way you are looking at. And also, im using a rigidbody3D, a character body is not a option for my game.
func _input(event: InputEvent) -> void:
if event is InputEventKey:
if Input.is_action_pressed("rotate_left"):
apply_force(Vector3(-1.0,0.0,0.0), Vector3(0.0,2.5,0.0))
elif Input.is_action_pressed("rotate_right"):
apply_force(Vector3(1.0,0.0,0.0), Vector3(0.0,2.5,0.0))
elif Input.is_action_pressed("rotate_foward"):
apply_force(Vector3(0.0,0.0,-1.0), Vector3(0.0,2.5,0.0))
elif Input.is_action_pressed("rotate_backward"):
apply_force(Vector3(0.0,0.0,1.0), Vector3(0.0,2.5,0.0))
also if you guys have any ideas on how to make this code more efficient that would be helpful thanks
What behavior does this code exhibit, and what behavior do you want it to make?
To make it slightly shorter, you could make a temporary constant that is Vector3(0.0, 2.5, 0.0) with a short name and replace the position argument with it. That way, you can change them by changing only one number, and the lines are shorter.
To fix your problem, you could create a dictionary of the force vectors, and on key press, grab the vector and rotate it by the rigid body rotation vector.
func _input(event: InputEvent) -> void:
if event is InputEventKey:
if Input.is_action_pressed("rotate_left"):
apply_force(Vector3(-1.0,0.0,0.0).rotated($center.transform.basis.z, $center.rotation.z), rocket_height) #if the $center node is PI / 4 rad left, rotate the force vector by that rotation.
elif Input.is_action_pressed("rotate_right"):
apply_force(Vector3(1.0,0.0,0.0).rotated($center.transform.basis.z, $center.rotation.z), rocket_height)
elif Input.is_action_pressed("rotate_foward"):
apply_force(Vector3(0.0,0.0,-1.0).rotated($center.transform.basis.x, $center.rotation.x), rocket_height)
elif Input.is_action_pressed("rotate_backward"):
apply_force(Vector3(0.0,0.0,1.0).rotated($center.transform.basis.x, $center.rotation.x), rocket_height)
Just rotate the force vectors by the rotation of your $center node. I don’t do much 3d, so 3d transforms are confusing to me. This code is untested and will probably not work first try. Let me know if you can figure it out. Link to transforms documentation here.
I was just thinking this morning that you might have to also rotate the rocket_height variable if it’s in global coordinates. If they are all in local coordinates, this shouldn’t be an issue.