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

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

7 8 9 10 11 12 13 14 15 16 17
	if ( center === undefined && radius === undefined ) {

		this.center = new THREE.Vector3();
		this.radius = 0;

	} else {

		this.center = center.clone();
		this.radius = radius || 0;

	}
18

19
};
20

21
THREE.Sphere.prototype = {
22

23
	constructor: THREE.Sphere,
24

25
	set: function ( center, radius ) {
26

27
		this.center.copy( center );
28 29 30
		this.radius = radius;

		return this;
31
	},
32

33 34 35
	setFromCenterAndPoints: function ( center, points ) {

		var maxRadiusSq = 0;
36 37 38 39

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

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

42 43 44 45 46 47
		}

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

		return this;
48

49 50
	},

51
	copy: function ( sphere ) {
52

53
		this.center.copy( sphere.center );
54
		this.radius = sphere.radius;
55 56

		return this;
57

58
	},
59

60
	empty: function () {
61 62

		return ( this.radius <= 0 );
63

64
	},
65

66
	containsPoint: function ( point ) {
67

68
		return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
69

70
	},
71

72
	distanceToPoint: function ( point ) {
73

74
		return ( point.distanceTo( this.center ) - this.radius );
75

76
	},
77

78
	clampPoint: function ( point ) {
79

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

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

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

86
			result.subSelf( this.center ).normalize();
87
			result.multiplyScalar( this.radius ).addSelf( this.center );
88

89 90
		}

91
		return result;
92

93
	},
94

95
	bounds: function () {
96

97
		var box =  new THREE.Box3( this.center, this.center );
98 99 100
		box.expandByScalar( this.radius );

		return box;
101

102
	},
103

104
	translate: function ( offset ) {
105

106
		this.center.addSelf( this.offset );
107

108
		return this;
109

110
	},
111

112
	scale: function ( factor ) {
B
Ben Houston 已提交
113 114

		this.radius *= factor;
115

B
Ben Houston 已提交
116
		return this;
117

118 119 120 121
	},

	equals: function ( sphere ) {

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

	},

	clone: function () {

		return new THREE.Sphere3().copy( this );

130
	}
B
Ben Houston 已提交
131

132
};