最近搜索

第03讲 创建我们的小车。在路上奔跑(可以左右走)

浏览:384
管理员 2021-11-12 03:03

创建一个空节点canvas 把gameCtl脚本拖到上面

image.png


添加关联我们的小车。

image.png








import { _decorator, Component, Node, systemEvent, SystemEventType, EventTouch, Touch, math, Vec3 } from 'cc';
import { MapManager } from './MapManager';
import { Player } from './Player';
const { ccclass, property } = _decorator;

@ccclass('GameCtl')
export class GameCtl extends Component {
    @property({
        type: MapManager,
    })
    mapManager: MapManager | null = null;


    @property({
        type: Player,
    })
    player: Player = null!;

    touch_x = 0;
    local_x = 0;
    currentZ = 0;
    @property
    speed = 0;

    private _state = 0; //0左  1右

    public start() {
        //this.mapManager.initMap("Map101");
        systemEvent.on(SystemEventType.TOUCH_START, this._touchStart, this);
        systemEvent.on(SystemEventType.TOUCH_END, this._touchEnd, this);
    }
    
    public update(dt: number) {
        this.currentZ += this.speed;
        if (this._state == 0) {
            //0左
            this.local_x =  this.local_x +  0.58;
        } else if (this._state  == 1) {
            //1右
            this.local_x =this.local_x -  0.58;
        }else if(this._state==-1){
        }
        this._state = -1;
        let pos = this.player.node.position.clone();
        //pos.z = this.currentZ;
        pos.x = math.lerp(pos.x, this.local_x,1);
        pos.x = this.local_x;
        this.player.node.setPosition(pos);

        this.player.node.parent.setPosition(new Vec3(0,0,this.currentZ));

    }

    private _touchStart(touch: Touch, event: EventTouch) {
        this.touch_x = touch.getLocation().x;
    }

    private _touchEnd(touch: Touch, event: EventTouch) {
        let end_x = touch.getLocation().x;
       
        let dis = this.touch_x - end_x;
        //灵敏度30
        if (dis > 30) {
            this._state  =0;
            console.log("左移");
        } else if (dis < -30) {
            this._state  =1;
            console.log("右移");
        }
    }


}




最后一步是做 镜头跟随小车。

创建一个空节点player 把小车和镜头全放里面。、

image.png


我们左右移动是小车在动

向前移动是镜头 向前。



联系站长

站长微信:xiaomao0055

站长QQ:14496453