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 ? new THREE.Vector3() : center.clone();
	this.radius = radius === undefined ? 0 : radius;
10

11
};
12

13
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 71 72 73 74

	isIntersectionSphere: function(sphere) {

		return ( sphere.center.distanceToSquared( this.center ) <= ( this.radius * this.radius + sphere.radius * sphere.radius) );
		
	},
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
			result.subSelf( this.center ).normalize();
86
			result.multiplyScalar( this.radius ).addSelf( 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.addSelf( 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

134
};