Djé Rèm
Djé Rèm

Reputation: 17

Three.js : Create an object on a surface and align it along the normal of this surface

I want to place arrows on an object when I click on it.

A JsFiddle is better than a long explanation :

https://jsfiddle.net/p820c246/4/

My source : https://github.com/mrdoob/three.js/issues/1486

It works well on the upper part of the surface but it bugs on lower part, I don't understand why. It seems that it bugs when the angle of the normal is to low. If you try whith a sphere like this it works well :

new T.SphereGeometry(1, 3, 2)

Thank you by advance

Upvotes: 0

Views: 3004

Answers (2)

pailhead
pailhead

Reputation: 5431

If you log the length of your axis axis.length() you will notice that it decreases as you increase the angle from up. It's still close to 1 on the 3rd row from the bottom, but is something like 0.7 on the second.

Change

var axis = new T.Vector3().crossVectors(up, normal)
.normalize(); //add this

and it will work

To be on the safe side, you could always normalize these axis, normals etc after a transformation and then optimize. Cross product's magnitude depends on the angle, and you used it further in operations that expect it to be unit length.

Upvotes: 1

Jessie Koffi
Jessie Koffi

Reputation: 176

That function orientAlongNormal does wayy too many math things. If I replace it with this:

function orientAlongNormal(object, coords, normal, scalar) {

  var up = new T.Vector3(0, 0, 1);
  object.up = up;//Z axis up

  //create a point to lookAt
  var newPoint = new THREE.Vector3(
      coords.x + normal.x,
      coords.y + normal.y,
      coords.z + normal.z
  );

  //aim object in direction of vector "normal" using lookAt
  object.lookAt(newPoint ); 

  //in this case the cone model is a bit wrong so we have to rotate it by 90 degrees
    object.rotateX( 0.5*Math.PI );

  //put object to coords
    object.position.addVectors(coords, normal.clone().multiplyScalar(scalar));
}

It works: https://jsfiddle.net/hanalulu/j9Lgeys7/

This thread helped me along the way: Issue aligning faces in Three.JS from two seperate objects

But the key takeaway for you is not to do complicated vector math stuff yourself and instead look for methods in the 3d engine that do it for you :)

Upvotes: 1

Related Questions