# Raycast on Phaser Camera3D Plugin

Last modified by Victor Zhang on 00:21, 22/07/2020

• The problem is actually discovered by a student when trying to implement a forward running game (They need to click the enemy)
• The camera3d class provides a ray function: https://photonstorm.github.io/phaser3-docs/Phaser.Cameras.Sprite3D.PerspectiveCamera.html#getPickRay__anchor
• In that way, calculating the x,y on the target plane and then do some hit-test manually would do the job
• Used example: http://labs.phaser.io/edit.html?src=src\camera\3D%20camera\floor.js
• Modify line  33 to : var balls = camera.createRect({ x: 8, y: 1, z: 8 }, 32, 'ball');
• Add following block to create():
balls.forEach( function(ball){
ball.setData('tag', 'ball'+ball.x+':'+ball.y+':'+ball.z);
} )

this.input.on('pointerdown', function (pointer) {

ray = camera.getPickRay(pointer.x, pointer.y);
balls.forEach( function(ball){
// r is hardcoded here
let r = 4;
// calculate x y @ z of the object
let tx, ty;
let tz = ball.z;
tx = ray.origin.x + ray.direction.x * (tz - ray.origin.z ) / ray.direction.z;
ty = ray.origin.y + ray.direction.y * (ray.origin.z - tz) / ray.direction.z;
let tl = Math.sqrt( Math.pow(tx - ball.x, 2) + Math.pow(ty - ball.y, 2) );
if( tl < r ){
console.log(ball.getData('tag')+' isHit');
ball.gameObject.alpha = 0;
}
} );

}, this);
• Explanation:
• the radius is hard coded here (5)
• more complex hit testing will need to be implemented for complex shapes
• manually enumerated through all object, inefficient (may need to implement some obvious exclusion for optimization)
• Extra problem
• Why is y axis reversed here?
• To study:
Created by Victor Zhang on 10:55, 18/05/2020