import { _decorator, Camera, Component, EventMouse, EventTouch, find, geometry, input, Input, Node, PhysicsSystem, RigidBody, v3 } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('f1')
export class f1 extends Component {
cameraCom: Camera = null
private _ray: geometry.Ray = new geometry.Ray()
ff1:Node = null
ff2:Node = null
ff3:Node = null
ff4:Node = null
sp1:number = -2
start() {
this.ff1 = find('l1/c2/s1')
this.ff2 = find('l1/c2/s2')
this.ff3 = find('l1/c2')
this.ff4 = find('l1/c2/s3')
this.cameraCom = find('m1').getComponent(Camera)
}
onEnable () {
input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
}
onDisable () {
input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
}
//触摸3D物体检测
onTouchStart(event:EventTouch){
const touch = event.touch!;
this.cameraCom.screenPointToRay(touch.getLocationX(), touch.getLocationY(), this._ray);
if (PhysicsSystem.instance.raycast(this._ray)) {
const raycastResults = PhysicsSystem.instance.raycastResults;
for (let i = 0; i < raycastResults.length; i++) {
const item = raycastResults[i];
if (item.collider.node == this.ff1) {
this.sp1 = 2
console.log('raycast hit the target node !');
break;
}
if (item.collider.node == this.ff2) {
this.sp1 = 0
console.log('raycast hit the target node !');
break;
}
if (item.collider.node == this.ff4) {
this.sp1 = -2
console.log('raycast hit the target node !');
break;
}
}
} else {
console.log('raycast does not hit the target node !');
}
}
update(deltaTime: number) {
//更新子碰撞体的位置
this.ff4.setPosition(this.ff4.position.x,this.ff4.position.y,this.ff4.position.z)
this.ff3.setPosition(this.ff3.position.x,this.ff3.position.y,this.ff3.position.z)
this.ff2.setPosition(this.ff2.position.x,this.ff2.position.y,this.ff2.position.z)
this.ff1.setPosition(this.ff1.position.x,this.ff1.position.y,this.ff1.position.z)
//动力
this.node.getComponent(RigidBody).setLinearVelocity(v3(0,this.sp1,0))
}
}