CocosCreator of KUOKUO teach you how to build a race track collision with tile map

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/kuokuo666/article/details/95728409

The engine v2.0.10

aims

Tile map generation race track crash

process

First,
we need to roll up a tile map.
Here Insert Picture Description
Very simple map, divided into two levels, walls and floors.

Then
directly dragged into the hierarchy manager in CocosCreator on the line.
Here Insert Picture Description
Then you will find layer nodes automatically form and mount the components.
Then to the wall and the car plus rigid
attention to the wall is a static rigid body, the car is moving, and I gave it to facilitate testing rotated 15 degrees.
As shown below:

Here Insert Picture Description
Here Insert Picture Description
Finally,
the use of getTileGIDAt this method to detect whether there are tiles.
There is a coordinate transformation, such as the top left corner of the tile 00 is converted coordinates -375,725.
Because I do it is map 1500 800 * 50 * 50 tiles.

const {ccclass, property} = cc._decorator;

@ccclass
export default class Main extends cc.Component {

    @property(cc.TiledLayer) wall: cc.TiledLayer = null;
    // 小车刚体
    @property(cc.RigidBody) car: cc.RigidBody = null;

    onLoad () {
        let p = cc.director.getPhysicsManager();
        p.enabled = true;
        p.debugDrawFlags = 1;
        // 关闭重力
        p.gravity = cc.v2(0, 0);
    }

    start () {
        // 地图为 16 * 30; 尺寸为 800 * 1500
        for (let i = 0; i < 16; i++) {
            for (let j = 0; j < 30; j++) {
                let n = this.wall.getTileGIDAt(i, j);
                console.log(n);
                // 如果存在瓦片,打印观察 n
                if (n != 0) {
                    // 计算位置, 800的一半是400 再加上方块长度的一半
                    let x = -400 + i * 50 + 25;
                    let y = 750 - j * 50 - 25;
                    // 加碰撞盒子
                    let p: cc.PhysicsBoxCollider = this.wall.node.addComponent(cc.PhysicsBoxCollider);
                    p.offset.set(cc.v2(x, y));
                    p.size.width = 50;
                    p.size.height = 50;
                    p.apply();
                }
            }
        }
    }

    update (dt) {
        // 一直给一个向前的力 测试用
        let hudu = cc.misc.degreesToRadians(this.car.node.rotation);
        let x = Math.sin(hudu);
        let y = Math.cos(hudu);
        this.car.applyForceToCenter(cc.v2(100 * x, 100 * y), false);
    }
}

effect

Here Insert Picture Description
O (∩ _ ∩) O ~ ~
the Get to not.

Add my blog :( QQ group inside the project, the group has a file oh)
706 176 551
We learn together!
O (∩_∩) O ~~

Guess you like

Origin blog.csdn.net/kuokuo666/article/details/95728409