Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

The sample code uses version three.js-R73: github.com/mrdoob/thre…

In the last video, we saw the problem of modeling a center point, but in this video we’re going to solve that problem, and we’re going to rotate the model around its center point. Let’s take a look.

Add a bounding box to the model

  • To make it easy to see the center of the model, we add a bounding box to the model
// The bounding box of the model
boxHelper = new THREE.BoxHelper(objMesh);
scene.add(boxHelper);
Copy the code
  • THREE.BoxHelper: secondary objects for graphically displaying axially aligned bounding boxes of the object world.

Center of computational model

  • Remember when we talked about how to deal with the model center
    • The center of the model can be calculated by finding the maximum and minimum value of XYZ in the bounding box.
    • By putting the model in the group and then moving the model somewhere in the group, we manipulate the group to look like the center of the model.

Create a group

pivot = new THREE.Group();
scene.add(pivot);
pivot.add(objMesh);

axis3 = new THREE.AxisHelper(100);
axis3.position.copy(pivot.position);
scene.add(axis3);
Copy the code
  • There is no change in effect at this point, the center of the grouping is at the origin, right
  • When you rotate a group, the model rotates around the group

Calculate the maximum and minimum points of the model

  • The following function returns the minimum and maximum points of the model
box = new THREE.Box3().setFromObject(objMesh);
Copy the code

  • So with the Max and the min we can figure out the center, and we passbox.center()You can set it directly

Calculates the model center position and moves to the group center

  • We move the model to the center axis of the group, and the model can rotate around the group in the center axis of the group
  • The distance moved is the distance from the center of the calculation -> the origin (the grouping center is at the origin)
box.center(objMesh.position)
Copy the code

  • As the calculated center point is a negative number, it is still a negative number from the original coordinate, resulting in the model moving to a negative distance
  • We have to multiply everything times minus 1
// Multiply all coordinates by a number
objMesh.position.multiplyScalar(-1)
Copy the code
  • multiplyScalar: This method inherits fromvector3

  • This is the time to rotate in the center of the group. We also need to move the center of the group to the original position of the model. The effect of the model rotation is to rotate around itself
// Assign the center of box to pivot. Position
box.center(pivot.position);
Copy the code

Codepen sample code