How can I rotate a Sprite to face particular x,y coordinates?

Three.js newb here.

I’m trying to figure out how to make a sprite rotate to face a particular coordinate. Like if the sprite is a turret and assuming the right side of the sprite is the “front”. I’d like the front to rotate towards specific xy coordinates.

sprite.material.rotation = // the xy coordinates that I'd like it to face.

How can I do this?

Sprites will always face the camera, spriteMaterial.rotation will rotate the texture on the z axis only, your best option for what you require is to use a plane with the texture attached and using .lookAt(vector3)

Oh, I think I didn’t explain what I’m trying to do very well.

I do want it as a sprite because it’ll always face the camera.

Think of it like 2D top-down video game and the sprite is a turret gun that rotates to face the mouse cursor. I just want to rotate the material so it’s always rotated towards the mouse cursor.

Made that funny example, where arrows on sprites rotate towards pointer.
Extended Sprite object. Passing in its constructor pointer’s position in NDC. In the update function, there is simple cast from scene coords into screen NDC for sprite’s position. Subtract sprite’s poisiton from pointer’s position. Call .angle(). Apply the result angle to sprite’s texture.

Picture:

Demo: https://codepen.io/prisoner849/full/BaVZKWW

PS Though, not sure how correct this approach is.

6 Likes

Thank you! This looks exactly what I’m looking for. I’ll go take a closer look at the code. :slight_smile:

Uh-oh… Coding at 1:30am… :yawning_face:
Forgot to take screen aspect in count. Updated the example :slight_smile:

2 Likes

that’s such a great solution

1 Like