想在脚本中获取指定节点Position,准备计算距离,却报错undefined。
报错信息:Uncaught TypeError: Cannot read property ‘swordsman’ of undefined
脚本内容:
swordsmandist: function () {
var swordsmanPos = this.forest.swordsman.getPosition();
var dist = cc.pDistance(fangPos, swordsmanPos);
return dist;
},
forest是什么类型?cc.Node?component?还是其他?
是脚本
你需要把forest脚本的内容和你当前的脚本的内容贴出来才能知道问题出在哪里,脚本你引用了吗?怎么引用的?swordsman是cc.node吗?
forest脚本的内容:
cc.Class({
extends: cc.Component,
properties: {
City: {
default: null,
type: cc.Prefab
},
swordsman: {
default: null,
type: cc.Node
},
},
onLoad: function () {
},
spawnNewStar: function() {
var newCity = cc.instantiate(this.CityPrefab);
this.node.addChild(newCity);
newCity.setPosition(297,-104);
newCity.getComponent('City').forest = this;
},
chuansong: function () {
cc.director.loadScene('Combat');
},
update: function(dt) {
},
});
City脚本:
cc.Class({
extends: cc.Component,
properties: {
Range: 0,
},
swordsmandist: function() {
var jiankePos = this.forest.swordsman.getPosition();
var dist = cc.pDistance(fangPos, swordsmanPos);
return dist;
},
move: function() {
this.forest.chuansong();
},
update: function(dt){
if (this.swordsmandist() < this.Range) {
this.move();
return;
}
},
});
这些是脚本内容
你这里swrodsmanPos哪里来的?
…这是之前写脚本时的命名错误,贴上来的时候忘记改了。
测试运行的时候,命名改好了的,改好后这一段内容是这样的:
swordsmandist: function() {
var swordsmanPos = this.forest.swordsman.getPosition();
var dist = cc.pDistance(this.node.position, swordsmanPos);
return dist;
},
但浏览器控制台报错:Uncaught TypeError: Cannot read property ‘swordsman’ of undefined
你的swordsman节点引用场景里的节点了吗?

是这里吗
是的,既然这样我也不知道为啥了
麻烦大神了
不麻烦,我也不是大神,如果有空的话做个demo传上来我可以帮你看看
好的,我试着做个demo
重新写了一遍,找到问题了……生成newprefab的方法没有调用……



话说,大大,我想再请教下,怎么通过子节点的按钮关闭按钮所在的界面窗口……
界面窗口写个close方法,active = false也好,destroy也好,然后添加到按钮的回调事件就行了啊,还有,我是野生小白,并不是啥大大
谢谢,好吧,不过至少在我看来是大大了
不好意思,麻烦了,再请教下……
active = false,destroy
这两个API,控制的节点必须是Node吗
我是通过主角移动到指定地点,自动弹出界面窗口的方法做的。
弹出界面的方式是通过newprefab的方法生成的。
layPrefab: {
default: null,
type: cc.Prefab
},
spawNewLay: function () {
var newLay = cc.instantiate(this.layPrefab);
this.node.addChild(newLay);
newLay.setPosition(12,-4);
}
移动到指定的节点后调用生成newprefab方法:
onPicked: function() {
this.game.spawNewLay();
},
close方法的脚本单独写的,挂载到Layout上,创建了一个Button节点后,把Layout组件放到了Button事件里,然后在Button上添加了回调事件,然后放进了Prefab里,能运行,也没有报错,但点击按钮界面没有反应。
close方法的脚本:
cc.Class({
extends: cc.Component,
properties: {
},
onLoad: function () {
},
move: function () {
cc.director.loadScene('MyScene');
},
close: function () {
this.node.destroy();
},
});
想请教下,关闭窗口界面没有反应,是哪里出了问题
是的,这两个都是node上的属性
能不能做个简单的demo我帮你看看,可能我语文没学好,根据你的描述想象不出来是怎样的
正确做法是把close方法写到你要关闭的节点的任何自定义脚本里,然后button回调的target是你挂载脚本的node,component就选你close方法所在的脚本,handler就是close方法