CocosCreator3D 从相机位置发射射线
程序员文章站
2022-06-11 11:42:27
...
需要给被射线检测到的物体添加碰撞器,脚本挂载到相机即可
import { _decorator, director, Component, Node, CanvasComponent, EventTouch, CameraComponent, ModelComponent, geometry, Touch, systemEvent, SystemEventType, PhysicsSystem, LabelComponent, Material } from "cc";
import { BtnEvent } from "./BtnEvent";
const { ccclass, property } = _decorator;
@ccclass("CameraRay")
export class CameraRay extends Component {
@property({ type: CameraComponent })
readonly camera_3d: CameraComponent = null;
@property({ type: Node })
Model: Node = null;
private _ray: geometry.ray = new geometry.ray();
btnE: BtnEvent;
start() {
this.btnE = this.node.getComponent(BtnEvent);
}
onEnable() {
systemEvent.on(SystemEventType.TOUCH_START, this.onTouchStart, this);
systemEvent.on(SystemEventType.TOUCH_END, this.onTouchEnd, this);
}
onDisable() {
systemEvent.off(SystemEventType.TOUCH_START, this.onTouchStart, this);
systemEvent.off(SystemEventType.TOUCH_END, this.onTouchEnd, this);
}
private x = 0;
private y = 0;
onTouchStart(touch: Touch, event: EventTouch) {
this.x = touch.getLocationX();
this.y = touch.getLocationY()
}
onTouchEnd(touch: Touch, event: EventTouch) {
if (touch.getLocationX() == this.x && touch.getLocationY() == this.y) {
this.camera_3d.screenPointToRay(touch.getLocationX(), touch.getLocationY(), this._ray);
//基于物理碰撞器的射线检测
if (PhysicsSystem.instance.raycast(this._ray)) {
const r = PhysicsSystem.instance.raycastResults;
for (let i = 0; i < r.length; i++) {
const item = r[i];
if (item.collider.node.uuid == this.Model.uuid) {
//射线检测到的物体如果是Model的话执行这里
}
}
}
}
}
}
上一篇: Django部署