[Cocos Creator] 踩坑日记(三)-路径移动问题及为其添加Promise

本文详细介绍了在Cocos Creator中如何处理人物模型在地图上的路径移动,包括路径生成、动态改变方向以及如何利用Promise解决移动结束后执行其他动作的回调问题。在移动过程中,用户可以随时改变目标点,导致原有的移动路径需要动态更新。文章最后讨论了Promise在处理移动结束回调中的应用,解决了旧Promise无法正确resolve的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:一个人物模型Actor与一张地图map,在地图上人物随意移动,比如能从A点到B点,或A点到B点过程中用户点击C点,那么改变移动方向到C点,在移动结束后执行其它人物动作Action

路径移动

首先我们能联想到的是cc.moveBy或cc.moveTo实现一格的移动,通过给出的路径path[ point1 , point2, ..., B]到达B点。

1. 生成路径path: generatePath(A, B, map?)(函数实现略)

2. 添加路径并移动: Actor.move(path)

    move( path){
        if( path == null || path == undefined || path. length == 0 )
            return;
        else{
            this . path = path ;
            this. _move( path);
        }
}

3. 一格移动: Actor._move(point)

    _move( path){
        // path = [ point1 , point2, ..., B]
        if( this. moveActions!= null && ! this. moveActions. isDone()) {
             // 上个动作没有完成,记录下path等之后完成
            this. path = path;
            return;
        } else{
            this. moveActions = new cc. ActionInterval();
            let nextSite = this. path. splice( 0, 1)[ 0];
            if( nextSite){
                 // 换算成网格移动所需要的x, y
                let x = ( nextSite. x - this. actor. x) * this. node. width,
                y = - ( nextSite. y - this. actor. y) * this. node. height;
                 // cc.moveBy移动一格,通过cc.sequence与cc.callFunc组合,实现移动一格结束后的回调
                this. moveActions = cc. sequence( cc. moveBy( MOVE_SPEED, x, y),
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值