2022-01-07 cocos creator 如何设置刚体跳上台阶的效果

在制作平台跳跃时,肯定少不了玩家跳上台阶的效果,该效果的机制是:

当玩家从下往上跳跃时,能穿过该台阶;
当玩家从上往下落时,能够站立停留在台阶上;

弄清楚该特性时,就知道该怎么做了,Collider2D组件具有 sensor 属性,该属性的作用为:

boolean类型。一个传感器类型的碰撞体会产生碰撞回调,但是不会发生物理碰撞效果。
通过,玩家上升时将sensor属性修改为true(能顺利穿过其他刚体),玩家下降至将sensor属性修改为false(能正常和其他刚体发生物理碰撞)。然后调用this.getComponent(Collider2D).apply() 来应用刚体的更改
代码如下:

        // 更改物体碰撞属性,该代码可放在玩家的跳跃函数里
        this.getComponent(Collider2D).sensor = true
        this.getComponent(Collider2D).apply()
        // 判断玩家下落时,sensor设置为false
        if (this.rigidbody.linearVelocity.y < 0) {
            this.getComponent(Collider2D).sensor = false
            this.getComponent(Collider2D).apply()
        }
    // 触摸一次屏幕跳跃功能
    /**
     * 触摸一次屏幕跳跃功能
     * @param touch 
     * @param event 
     * @returns 
     */
    onTouchStartCallback(touch, event: EventTouch) {

        let linear = this.rigidbody.linearVelocity
        // 禁止在空中触发跳跃
        if (linear.y != 0) {
            return
        }
        let lx = linear.x / Math.abs(linear.x) * this.speed
        this.rigidbody.linearVelocity = v2(linear.x, this.jumpHeight)

        // 更改穿透属性
        this.getComponent(Collider2D).sensor = true
        this.getComponent(Collider2D).apply()
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容