Browse Source

Add sprite.raycast support for scale,rotation,center

06wj 7 years ago
parent
commit
1831377e21
1 changed files with 21 additions and 2 deletions
  1. 21 2
      src/objects/Sprite.js

+ 21 - 2
src/objects/Sprite.js

@@ -1,5 +1,6 @@
 import { Vector2 } from '../math/Vector2.js';
 import { Vector3 } from '../math/Vector3.js';
+import { Matrix4 } from '../math/Matrix4.js';
 import { Object3D } from '../core/Object3D.js';
 import { SpriteMaterial } from '../materials/SpriteMaterial.js';
 
@@ -31,13 +32,31 @@ Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
 		var intersectPoint = new Vector3();
 		var worldPosition = new Vector3();
 		var worldScale = new Vector3();
+		
+		var alignedPosition = new Vector2();
+		var rotatedPosition = new Vector2();
+		var matrixWorldInverse = new Matrix4();
 
 		return function raycast( raycaster, intersects ) {
 
-			worldPosition.setFromMatrixPosition( this.matrixWorld );
+			worldScale.setFromMatrixScale( this.matrixWorld );
+
+			// compute position in camera space
+			alignedPosition.set( ( 0.5 - this.center.x  ) * worldScale.x, ( 0.5 - this.center.y ) * worldScale.y );
+			
+			var rotation = this.material.rotation;
+			rotatedPosition.x = (Math.cos(rotation) * alignedPosition.x) - (Math.sin(rotation) * alignedPosition.y);
+			rotatedPosition.y = (Math.sin(rotation) * alignedPosition.x) + (Math.cos(rotation) * alignedPosition.y);
+			
+			worldPosition.setFromMatrixPosition( this.modelViewMatrix );
+			worldPosition.x += rotatedPosition.x;
+			worldPosition.y += rotatedPosition.y;
+
+			// transform to world space
+			worldPosition.applyMatrix4( matrixWorldInverse.getInverse( this.modelViewMatrix ) ).applyMatrix4( this.matrixWorld );
+			
 			raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
 
-			worldScale.setFromMatrixScale( this.matrixWorld );
 			var guessSizeSq = worldScale.x * worldScale.y / 4;
 
 			if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;