<八>角色控制

实现角色的左右移动就是给其施加一个向左或向右的力。
输入事件通过Input来监听(Input监听的事件注意在析构函数中取消)

import { _decorator, Component, EventKeyboard, Input, input, KeyCode, Node, RigidBody, v3, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerMovement')
export class PlayerMovement extends Component {
    @property(Number)
    forwardForce: number = 500;
    @property(Number)
    sideForce: number = 1000;
    _tempVec:Vec3 = v3();
    isLeftDown:boolean = false;
    isRightDown:boolean = false;
    start() {
        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_A) {
           this.isLeftDown = true;
       }else if(event.keyCode == KeyCode.KEY_D) {
           this.isRightDown = true;
       }
    }
    onkeyUp(event: EventKeyboard) {
        if(event.keyCode == KeyCode.KEY_A) {
            this.isRightDown = false;
        }else if(event.keyCode == KeyCode.KEY_D) {
            this.isLeftDown = false;

        }
    }

    update(deltaTime: number) {
        const rigidbody = this.getComponent(RigidBody);
        this._tempVec.x = 0;
        this._tempVec.y = 0;
        this._tempVec.z = this.forwardForce * deltaTime;
        rigidbody.applyForce(this._tempVec);

        if(this.isLeftDown){
            this._tempVec.x = this.sideForce * deltaTime;
            this._tempVec.y = 0;
            this._tempVec.z = 0;
            rigidbody.applyForce(this._tempVec);
        }
        if(this.isRightDown){
            this._tempVec.x = -this.sideForce * deltaTime;
            this._tempVec.y = 0;
            this._tempVec.z = 0;
            rigidbody.applyForce(this._tempVec);
        }
    }

    protected onDestroy(): void {
        input.off(Input.EventType.KEY_DOWN,this.onkeyDown,this);
        input.off(Input.EventType.KEY_UP,this.onkeyUp,this);
    }
}


运行预览

posted @ 2024-12-17 13:48  EricShx  阅读(15)  评论(0)    收藏  举报