import { _decorator, BoxCollider, CapsuleCollider, CharacterController, Component, EventKeyboard, EventMouse, geometry, Input, input, KeyCode, Node, physics, PhysicsGroup, PhysicsSystem, RigidBody, v2, v3, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('c1')
export class c1 extends Component {
sp1: number = 2
res1: Vec3 = v3(0, 0, 0)
x1: number = 0
z1: number = 0
characterController: CharacterController = null
mask = 0xffffffff;
maxDistance = 10000000;
queryTrigger = false
@property({ type: physics.PhysicsGroup })
group1: PhysicsGroup
start() {
this.characterController = this.node.getComponent(CharacterController)
//旋转视角
input.on(Input.EventType.MOUSE_MOVE, this.onMouseMove, this)
input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this)
input.on(Input.EventType.KEY_UP, this.onKeyUp, this)
}
onKeyDown(event: EventKeyboard) {
if (event.keyCode == KeyCode.KEY_W) {
this.z1 = -1
}
if (event.keyCode == KeyCode.KEY_A) {
this.x1 = -1
}
if (event.keyCode == KeyCode.KEY_S) {
this.z1 = 1
}
if (event.keyCode == KeyCode.KEY_D) {
this.x1 = 1
}
}
onKeyUp(event: EventKeyboard) {
if (event.keyCode == KeyCode.KEY_W) {
this.z1 = 0
}
if (event.keyCode == KeyCode.KEY_A && this.x1 == -1) {
this.x1 = 0
}
if (event.keyCode == KeyCode.KEY_S) {
this.z1 = 0
}
if (event.keyCode == KeyCode.KEY_D && this.x1 == 1) {
this.x1 = 0
}
}
//旋转视角
onMouseMove(event: EventMouse) {
if (event.getButton() == 2) {
//获取本地坐标系下的旋转,用欧拉角表示
let fe1 = this.node.eulerAngles.x
let fe2 = this.node.eulerAngles.y
//鼠标在UI坐标系下的移动距离
let x1 = event.movementX * 0.5
let y1 = event.movementY * 0.5
//用欧拉角设置世界坐标系下的旋转
fe1 += -y1
fe2 += -x1
if (fe1 > -80 && fe1 < 80) {
this.node.setRotationFromEuler(fe1, fe2, 0)
}
}
}
update(deltaTime: number) {
// 根据自身方向,转化方向
this.res1 = new Vec3(this.x1 * this.sp1 * deltaTime, 0, this.z1 * this.sp1 * deltaTime);
//获取节点的本地化局部旋转方向,1:返回值,2:需要转换的方向向量,3:当前本地旋转
Vec3.transformQuat(this.res1, this.res1, this.node.getWorldRotation());
//在载具外移动的方式
if (this.characterController.enabled && !this.node.getComponents(CapsuleCollider)[0].enabled) {
this.characterController.move(v3(this.res1.x, -0.2, this.res1.z));
}
//在载具内移动的方式
if (this.node.getComponents(CapsuleCollider)[0].enabled && !this.characterController.enabled) {
this.node.setPosition(this.node.position)
let z1 = this.node.worldPosition
let ray1 = geometry.Ray.create(z1.x, z1.y, z1.z, this.res1.x, 0, this.res1.z)
if (PhysicsSystem.instance.raycastClosest(ray1, this.group1, 1.2, this.queryTrigger)) {
let s1 = PhysicsSystem.instance.raycastClosestResult.distance
console.log(s1 + 'sssss')
this.node.setWorldPosition(z1.x, z1.y, z1.z)
return
}
this.node.setWorldPosition(this.res1.x + z1.x, z1.y, this.res1.z + z1.z)
}
}
}