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
	set: function ( center, radius ) {
16

17
		this.center.copy( center );
18 19 20
		this.radius = radius;

		return this;
21
	},
22

23 24 25
	setFromCenterAndPoints: function ( center, points ) {

		var maxRadiusSq = 0;
26 27 28 29

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

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

32 33 34 35 36 37
		}

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

		return this;
38

39 40
	},

41
	copy: function ( sphere ) {
42

43
		this.center.copy( sphere.center );
44
		this.radius = sphere.radius;
45 46

		return this;
47

48
	},
49

50
	empty: function () {
51 52

		return ( this.radius <= 0 );
53

54
	},
55

56
	containsPoint: function ( point ) {
57

58
		return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
59

60
	},
61

62
	distanceToPoint: function ( point ) {
63

64
		return ( point.distanceTo( this.center ) - this.radius );
65

66
	},
O
Oliver Sand 已提交
67

68
	intersectsSphere: function ( sphere ) {
O
Oliver Sand 已提交
69

70 71
		var radiusSum = this.radius + sphere.radius;

72 73
		return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );

O
Oliver Sand 已提交
74
	},
75

76
	clampPoint: function ( point, optionalTarget ) {
77

78
		var deltaLengthSq = this.center.distanceToSquared( point );
79

80 81
		var result = optionalTarget || new THREE.Vector3();
		result.copy( point );
82

83
		if ( deltaLengthSq > ( this.radius * this.radius ) ) {
84

85 86
			result.sub( this.center ).normalize();
			result.multiplyScalar( this.radius ).add( this.center );
87

88 89
		}

90
		return result;
91

92
	},
93

94
	getBoundingBox: function ( optionalTarget ) {
95

96 97 98
		var box = optionalTarget || new THREE.Box3();

		box.set( this.center, this.center );
99 100 101
		box.expandByScalar( this.radius );

		return box;
102

103
	},
104

105
	transform: function ( matrix ) {
106

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

		return this;

	},

114
	translate: function ( offset ) {
115

116
		this.center.add( offset );
117

B
Ben Houston 已提交
118
		return this;
119

120 121 122 123
	},

	equals: function ( sphere ) {

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

	},

	clone: function () {

130
		return new THREE.Sphere().copy( this );
131

132
	}
B
Ben Houston 已提交
133

M
Mr.doob 已提交
134
} );