How can I set the rotation of an object based on position vector?

Hello!

I am currently working on making a game with Three.js

In this game the player controls a character that is on a small planet (a sphere) which has it’s own orbit. I want the character to rotate with the sphere so if they are on the bottom of it the character will be rotated upside down.

The center of the sphere (planet) is at (0,0,0). So I was able to achieve this effect with the following code:

this.gltf.scene.up = this.getPosition().clone().normalize()
player1.gltf.scene.lookAt(new Vector3())
player1.gltf.scene.rotateX(-Math.PI/2)

However I am now encountering an issue where I can’t set the character’s rotation based on the user input. Like, if the character is moving left I want them to face left as well. But they only face one direction and no matter what I do I can’t seem to fix this. I’ve tried applying quaternions, rotateY, Euler, etc. I believe my code above might be hacky and that’s why I can’t change the character’s direction.

Does anyone have any ideas?

I’ve also tried the following code to set the character’s rotation. I get the quaternion between up (0,1,0) and the character’s position and then apply it to the character which also does not work

var testQuat = new Quaternion().setFromUnitVectors(new Vector3(0,1,0), nextPos.clone().normalize())
player1.gltf.scene.applyQuaternion(testQuat)

I ended up changing the code to:

this.gltf.scene.up = this.getPosition().clone().normalize()
this.gltf.scene.quaternion.setFromUnitVectors(new Vector3(0,1,0), nextPos.clone().normalize())

Which seems work work a lot better

1 Like