I am making a game where you have a sword that you can swing, the sword is in a group with an offset so it is positioned right. I am trying to make it so that when I press Z the sword swings down and then back up via rotation. how do I get the sword to swing in the direction I face? Currently, I have if (keys.z) group.rotation.x -= Math.PI/100;
, but that only works for the x-axis. The model copes the camera position with group.position.copy(camera.position);
, and quaternion with if(!keys.z)group.quaternion.copy(camera.quaternion);
.
One way I thought do do it was to change the sword's rotation offset but I don't know how to do that, would that even work? Anyways please help I love coding and want to make this game!
The camera, like many other in-scene objects, is based on Object3D
. This means you can add scene nodes to it, and they will exist in the camera's local space.
camera.add( swordMesh )
Think of the camera as having its own space around it that is independent from the world space. The camera sits at (0, 0, 0)
, with -Z extending forward, +Z extending backward, +Y extending upward, -Y is downward, +X goes right and -X goes left.
Now, if you place your "sword" somewhere in the +X, -Y, -Z
direction, it will be in front of, below, and to the right, within the view. The bonus here is that if you move or rotate the camera in any way, the sword follows.
camera.add( swordMesh )
sword.position.set( 10, -10, -10 ) // coordinates are local to camera space
To swing the sword away from the camera, rotate it about the X axis, which, since it's a child of the camera, is automatically the camera's X axis.