Sphere.js 2.3 KB
Newer Older
1
/**
B
Ben Houston 已提交
2
 * @author bhouston / http://exocortex.com
3
 * @author mrdoob / http://mrdoob.com/
4 5
 */

6
THREE.Sphere = function ( center, radius ) {
7

8 9
	this.center = ( center !== undefined ) ? center : new THREE.Vector3();
	this.radius = ( radius !== undefined ) ? radius : 0;
10

11
};
12

13
THREE.extend( THREE.Sphere.prototype, {
14

15
	constructor: THREE.Sphere,
16

17
	set: function ( center, radius ) {
18

19
		this.center.copy( center );
20 21 22
		this.radius = radius;

		return this;
23
	},
24

25 26 27
	setFromCenterAndPoints: function ( center, points ) {

		var maxRadiusSq = 0;
28 29 30 31

		for ( var i = 0, il = points.length; i < il; i ++ ) {

			var radiusSq = center.distanceToSquared( points[ i ] );
32
			maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
33

34 35 36 37 38 39
		}

		this.center = center;
		this.radius = Math.sqrt( maxRadiusSq );

		return this;
40

41 42
	},

43
	copy: function ( sphere ) {
44

45
		this.center.copy( sphere.center );
46
		this.radius = sphere.radius;
47 48

		return this;
49

50
	},
51

52
	empty: function () {
53 54

		return ( this.radius <= 0 );
55

56
	},
57

58
	containsPoint: function ( point ) {
59

60
		return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
61

62
	},
63

64
	distanceToPoint: function ( point ) {
65

66
		return ( point.distanceTo( this.center ) - this.radius );
67

68
	},
O
Oliver Sand 已提交
69

70
	intersectsSphere: function ( sphere ) {
O
Oliver Sand 已提交
71

72 73
		var radiusSum = this.radius + sphere.radius;

74 75
		return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );

O
Oliver Sand 已提交
76
	},
77

78
	clampPoint: function ( point, optionalTarget ) {
79

80
		var deltaLengthSq = this.center.distanceToSquared( point );
81

82 83
		var result = optionalTarget || new THREE.Vector3();
		result.copy( point );
84

85
		if ( deltaLengthSq > ( this.radius * this.radius ) ) {
86

87 88
			result.sub( this.center ).normalize();
			result.multiplyScalar( this.radius ).add( this.center );
89

90 91
		}

92
		return result;
93

94
	},
95

96
	getBoundingBox: function ( optionalTarget ) {
97

98 99 100
		var box = optionalTarget || new THREE.Box3();

		box.set( this.center, this.center );
101 102 103
		box.expandByScalar( this.radius );

		return box;
104

105
	},
106

107
	transform: function ( matrix ) {
108

109
		this.center.applyMatrix4( matrix );
110 111 112 113 114 115
		this.radius = this.radius * matrix.getMaxScaleOnAxis();

		return this;

	},

116
	translate: function ( offset ) {
117

118
		this.center.add( offset );
119

B
Ben Houston 已提交
120
		return this;
121

122 123 124 125
	},

	equals: function ( sphere ) {

A
alteredq 已提交
126
		return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
127 128 129 130 131

	},

	clone: function () {

132
		return new THREE.Sphere().copy( this );
133

134
	}
B
Ben Houston 已提交
135

136
} );