Line data Source code
1 : import { clamp } from 'es-toolkit'
2 :
3 : import type { Vector3Like } from 'three'
4 :
5 2355 : const RAD2DEG = 180 / Math.PI
6 2355 : const DEG2RAD = Math.PI / 180
7 :
8 2355 : export const MIN_DISTANCE = 0.5
9 : export const MAX_DISTANCE = 100
10 : export const MIN_PITCH = -89
11 : export const MAX_PITCH = 89
12 :
13 0 : export function pointToYawAngle(
14 : point: Vector3Like,
15 : target: Vector3Like
16 : ): number {
17 0 : return Math.atan2(point.x - target.x, point.z - target.z) * RAD2DEG
18 : }
19 :
20 0 : export function pointToPitchAngle(
21 : point: Vector3Like,
22 : target: Vector3Like,
23 : yawDeg: number
24 : ): number {
25 0 : const y = yawDeg * DEG2RAD
26 0 : const dx = point.x - target.x
27 0 : const dy = point.y - target.y
28 0 : const dz = point.z - target.z
29 0 : const horizontal = dx * Math.sin(y) + dz * Math.cos(y)
30 0 : const raw = Math.atan2(dy, horizontal) * RAD2DEG
31 0 : return clamp(raw, MIN_PITCH, MAX_PITCH)
32 : }
33 :
34 0 : export function pointToDistance(
35 : point: Vector3Like,
36 : target: Vector3Like,
37 : yawDeg: number,
38 : pitchDeg: number
39 : ): number {
40 0 : const y = yawDeg * DEG2RAD
41 0 : const p = pitchDeg * DEG2RAD
42 0 : const dirX = Math.cos(p) * Math.sin(y)
43 0 : const dirY = Math.sin(p)
44 0 : const dirZ = Math.cos(p) * Math.cos(y)
45 0 : const dx = point.x - target.x
46 0 : const dy = point.y - target.y
47 0 : const dz = point.z - target.z
48 0 : const projection = dx * dirX + dy * dirY + dz * dirZ
49 0 : return clamp(projection, MIN_DISTANCE, MAX_DISTANCE)
50 : }
|