见鬼了,运算的结果赋值给变量,竟然还会变

  • Creator 版本: 2.4.5

用for循环创建6个节点,分别在6个位置,通过算法赋值给变量,但是位置不是我想要的位置,我以为是算法算的不对,然后log出来看一下,赋值之后的数竟然会变,这是什么逻辑,大佬们帮看看
this.picArr = [];
for (let i = 0; i < 2; i++) {
this.picArr[i] = [];
for (let j = 0; j < 3; j++) {
this.picArr[i][j] = cc.instantiate(this.block);
this.picArr[i][j].parent = background;
let margin = 50;
let parentWidht = this.node.width;
let parentHeight = this.node.height;
let targetPosX = Math.abs(i * (parentWidht - this.picArr[i][j].width) - margin);
let targetPosY = (- parentHeight + this.picArr[i][j].height) / 2 * j + (j - 1) * margin;
this.picArr[i][j].getComponent(‘block’).init(texture, cc.v2(j, i));
this.picArr[i][j].setPosition(cc.v2(targetPosX, targetPosY));
cc.log(targetPosX, targetPosY);
cc.log(Math.abs(i * (parentWidht - this.picArr[i][j].width) - margin), (- parentHeight + this.picArr[i][j].height) / 2 * j + (j - 1) * margin);
}
}
log出来的结果竟然是这样的,除了第一个节点的位置是正确的,其他的位置都不对,我就看不懂是哪里出问题了
50 -50
50 -50
50 -320
50 -162.5
50 -590
50 -275
910 -50
548 -50
910 -320
548 -162.5
910 -590
548 -275

这里就这两个可能会变,

你检查一下这个方法里干了什么,是不是发生了尺寸变化,texture的设置可能是会改变尺寸的

没有,生成的6个节点的尺寸是一样的,这个可以确定,这个在预制的组件里边就设定了的,是用一张图片分成6个尺寸一样的区域,width和height都是固定的,所以才直接那么些的
init(picTexture, pos) {
let width = picTexture.width / 2;
let height = picTexture.height / 3;
let sprite = this.node.addComponent(cc.Sprite);
this.node.setContentSize(width, height);
this.node.scale = 0.5;
this.node.setAnchorPoint(0, 1);
sprite.spriteFrame = new cc.SpriteFrame(picTexture, cc.rect(pos.x * width, pos.y * height, width, height));
},

你分别把各个变量打印出来,对比前后变化,就知道那个变量出了问题了

加上了两个log
cc.log(targetPosX, targetPosY);
cc.log(Math.abs(i * (parentWidht - this.picArr[i][j].width) - margin), (- parentHeight + this.picArr[i][j].height) / 2 * j + (j - 1) * margin);
cc.log(this.picArr[i][j].width,this.picArr[i][j].height);
cc.log(parentWidht,parentHeight);
结果是这样的
50 -50
50 -50
362 315
960 640
50 -320
50 -162.5
362 315
960 640
50 -590
50 -275
362 315
960 640
910 -50
548 -50
362 315
960 640
910 -320
548 -162.5
362 315
960 640
910 -590
548 -275
362 315
960 640

我要你打印前后变化呀,就是init之前打印一遍各个变量,init之后再打印各个变量
或许你打断点看就行了

谢谢,确实是问题在init这里,init之前节点的尺寸是0,0,init之后才有的尺寸,多谢大佬!

该主题在最后一个回复创建后14天后自动关闭。不再允许新的回复。