注意点:
1、开启射线检测
cc.director.getPhysics3DManager().enabled = true;
2: 响应射线的物体要加3D碰撞盒 BoxCollider3D
3:响应射线的物体分组group要设置为3D,分组管理里需要勾选3D和3D的碰撞
demo下载:
typescript
const { ccclass, property } = cc._decorator;
@ccclass
export default class CameraTouchCtrl extends cc.Component {
@property(cc.Camera)
camera: cc.Camera = null;//3D相机
@property(cc.Node)
touchNode: cc.Node = null;//2D触摸节点
start() {
//开启射线检测
cc.director.getPhysics3DManager().enabled = true;
this.touchNode.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
}
/**检测射线 */
onTouchStart(event) {
let touchLoc = event.touch.getLocation();
let ray = this.camera.getComponent(cc.Camera).getRay(touchLoc);
let maxDistance = 1000;//检测的最远距离,如果物体远,需要改大数值
let rayColliderGroupName = "3D";//碰撞分组,分组管理里需要勾选3D和3D动碰撞
//响应射线的物体要加3D碰撞盒 BoxCollider3D,分组group设置为3D
const result = cc.director.getPhysics3DManager().raycastClosest(ray, rayColliderGroupName, maxDistance, false);
if (result) {
let box = result.collider.node
box.scale += 0.01
}
}
}