时间:2022-4-3 作者:虣虣 分类: CocosCreator
结果
第一步:如图所示,在场景中新建一个Cube,为Cube添加一个3D BoxCoxCollider 组件
第二步:新建一个脚本文件(比如:GameContorll),挂着任意一个节点上面。在start()函数中监听触摸事件
@ccclass('GameContorll')
export class GameContorll extends Component {
start () {
input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
}
onTouchStart(event: EventTouch) {
}
}
第三部:利用摄像机进行射线检查
/*
* @Descripttion:
* @version: 1.0
* @Author: 虣虣
* @Date: 2022-04-03 01:59:23
* @LastEditTime: 2022-04-03 12:58:57
*/
import { _decorator, Component, Node, Camera, geometry, systemEvent, input, Input, EventTouch, PhysicsSystem } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('GameContorll')
export class GameContorll extends Component {
@property({type: Camera, displayName: "主摄像机"})
public mainCamera: Camera = null;
@property({type: Node, displayName: "带触摸的物体"})
public ndTouchNode: Node = null;
private _ray: geometry.Ray = new geometry.Ray();
start () {
input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
}
onTouchStart(event: EventTouch) {
// 基于摄像机画射线
this.mainCamera.screenPointToRay(event.getLocation().x, event.getLocation().y, this._ray);
// 基于物理碰撞器的射线检查
if (PhysicsSystem.instance.raycast(this._ray)) {
let r = PhysicsSystem.instance.raycastResults;
for (let index = 0; index < r.length; index++) {
let element = r[index];
if (element.collider.node.uuid === this.ndTouchNode.uuid) {
console.log("点击到物体了");
}
}
}
}
}