Quantcast
Viewing all articles
Browse latest Browse all 89251

求帮助!入门教程中收集星星报错Cannot read property 'getPosition' of undefined

@632294730 写道:

刚刚入门Cocos Creator,再做第一个游戏收集星星时,在主角碰到星星,星星消失时遇到问题。实在搞不明白,也折腾了很久,求各位大佬帮忙。
另外第一次用社区,要是有什么提问不合适什么的地方还请大佬指出并包涵!谢谢!

报错信息指Star类中getPlayerDistance方法调用getPosition错误
TypeError: Cannot read property 'getPosition' of undefined
但我按照教程在Game里面为它赋值了呀

Star类
cc.Class({
extends: cc.Component,

properties: {
    // 星星和主角之间的距离小于这个数值时,就会完成收集
    pickRadius: 200,
},
onLoad(){
},

// Star.js
getPlayerDistance: function () {
// 根据 player 节点位置判断距离
var playerPos = this.game.player.getPosition();
// 根据两点位置计算两点之间距离
var dist = this.node.position.sub(playerPos).mag();
return dist;
},

onPicked: function() {
// 当星星被收集时,调用 Game 脚本中的接口,生成一个新的星星
this.game.spawnNewStar();
// 然后销毁当前星星节点
this.node.destroy();
},
start () {

},
update: function (dt) {
// 每帧判断和主角之间的距离是否小于收集距离
if (this.getPlayerDistance() < this.pickRadius) {
// 调用收集行为
this.onPicked();
return;
}
},
});

Game类
........
spawnNewStar: function() {
// 使用给定的模板在场景中生成一个新节点
var newStar = cc.instantiate(this.starPrefab);
// 将新增的节点添加到 Canvas 节点下面
this.node.addChild(newStar);
// 为星星设置一个随机位置
newStar.setPosition(this.getNewStarPosition());
newStar.getComponent('Star').game = this;
},
........

帖子: 1

参与者: 1

阅读整个主题


Viewing all articles
Browse latest Browse all 89251

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>