欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CocosCreator3D鼠标拖拽相机旋转,第一人称旋转

程序员文章站 2022-06-11 11:41:51
...

直接挂载到相机即可

import { _decorator, Component, math, UITransformComponent, EventTouch, Touch, Node, LabelComponent, CameraComponent, systemEvent } from "cc";

const { ccclass, property } = _decorator;
const { Vec2, Vec3, Quat } = math;

const v2_1 = new Vec2();
const v2_2 = new Vec2();
const v3_1 = new Vec3();
const qt_1 = new Quat();
const KEYCODE = {
    W: 'W'.charCodeAt(0),
    S: 'S'.charCodeAt(0),
    A: 'A'.charCodeAt(0),
    D: 'D'.charCodeAt(0),
    Q: 'Q'.charCodeAt(0),
    E: 'E'.charCodeAt(0),
    SHIFT: cc.macro.KEY.shift,
};

@ccclass("Camera")
export class camera extends Component {

    @property(LabelComponent)
    log: LabelComponent | null = null;

    @property
    moveSpeed = 1;

    @property
    moveSpeedShiftScale = 5;

    @property({ slide: true, range: [0.05, 0.5, 0.01] })
    damp = 0.2;

    @property
    rotateSpeed = 1;

    _euler = new Vec3();
    _velocity = new Vec3();
    _position = new Vec3();
    _speedScale = 1;


    onLoad() {
        cc.systemEvent.on(cc.SystemEvent.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_START, this.onTouchStart, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_MOVE, this.onTouchMove, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_END, this.onTouchEnd, this);
        Vec3.copy(this._euler, this.node.eulerAngles);
        Vec3.copy(this._position, this.node.position);
    }

    onDestroy() {
        cc.systemEvent.off(cc.SystemEvent.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
        cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_START, this.onTouchStart, this);
        cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_MOVE, this.onTouchMove, this);
        cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    update(dt) {
        Quat.fromEuler(qt_1, this._euler.x, this._euler.y, this._euler.z);
        Quat.slerp(qt_1, this.node.rotation, qt_1, dt / this.damp);
        this.node.setRotation(qt_1);
    }

    onMouseWheel(e) {
        const delta = -e.getScrollY() * this.moveSpeed * 0.1; // delta is positive when scroll down
        Vec3.transformQuat(v3_1, Vec3.UNIT_Z, this.node.rotation);
        Vec3.scaleAndAdd(this._position, this.node.position, v3_1, delta);
    }

    onTouchStart(_e) {
        if (cc.game.canvas.requestPointerLock) cc.game.canvas.requestPointerLock();

        let location = _e.getLocation();// 获取节点坐标
    }
    onTouchMove(e, even) {

        let touches = even.getTouches();

        if (touches.length == 1) {
            e.getStartLocation(v2_1);
            if (v2_1.x > cc.winSize.width * 0.4) { // rotation
                e.getDelta(v2_2);
                this._euler.y += v2_2.x * this.rotateSpeed * 0.1;
                this._euler.x -= v2_2.y * this.rotateSpeed * 0.1;
            }
        }

    }

}