所以我正在尝试为游戏动态添加一些障碍,现在这是与此相关的整个代码:
cc.Class({
extends: cc.Component,
properties: {
ObstaclesGap: 180,
Alive: true,
XChange: 300,
LastLowerX: 0,
UpperObstacleSpritePrefab: cc.Prefab,
LowerObstacleSpritePrefab: cc.Prefab,
},
generateObstacle() {
// Creation of obstacles
const lowerObstacle = cc.instantiate(this.LowerObstacleSpritePrefab);
const upperObstacle = cc.instantiate(this.UpperObstacleSpritePrefab);
// Addition to canvas
this.node.addChild(lowerObstacle);
this.node.addChild(upperObstacle);
// Setting sizes
lowerObstacle.width = 60;
upperObstacle.width = 60;
/*
Generates a number between 1 - 10, and multiply the lower obstacle's height with that number.
The rest is then equals to the upper obstacle's height.
All of that with a remaining 180 gap between them all of the time (which is 3 times the size of the bird)
*/
const rndNumber1t10 = Math.floor(Math.random() * 10)+1;
lowerObstacleHeight = 540 * (rndNumber1t10 / 10);
upperObstacleHeight = 540 * ((10 - rndNumber1t10) / 10);
lowerObstacle.height = lowerObstacleHeight;
upperObstacle.height = upperObstacleHeight;
// Preperations for next obstacle positions
lowerObstacle.getComponent(cc.PhysicsBoxCollider).size = cc.Size(60, lowerObstacleHeight)
upperObstacle.getComponent(cc.PhysicsBoxCollider).size = cc.Size(60, upperObstacleHeight)
this.LastLowerX += this.XChange;
// Setting positions with a gap between the obstacles (720 - 180 = 540)
lowerObstacle.setPosition(cc.v2(parseInt((-this.node.x) + this.LastLowerX), parseInt((-this.node.y) + 100 + lowerObstacleHeight / 2)));
upperObstacle.setPosition(cc.v2(parseInt((-this.node.x) + this.LastLowerX), parseInt((-this.node.y) + 720)));
},
onLoad() {
for (let i = 0; i < 1; i++) {
this.generateObstacle();
}
},
start() {
},
// update (dt) {},
});
这是我的组经理:
这是 Prefebs 之一的示例:
问题是小鸟和障碍物之间不会发生碰撞,但是如果我手动拖动到游戏中,它会发生碰撞,所以我的代码一定有问题。