Cocos Creator中用Action旋转Node报错:cc.RotateBy.create不是函数
解决Cocos Creator中
cc.RotateBy.create is not a function错误 嘿,刚接触Cocos Creator的话很容易踩版本API差异的坑,我来帮你捋清楚问题:
首先先揪出你代码里的一个小bug——你两行都写了this.node.getChildByName("gateLeft"),右边的门应该是gateRight,这个先改了,不然两个动作都会作用在左门上,白忙活一场。
然后是核心的cc.RotateBy.create is not a function错误,这是因为Cocos Creator的API在v3.x版本做了大调整,旧版的.create()创建动作的方式已经被淘汰了,下面分版本给你解决方案:
如果你用的是Cocos Creator v3.x(目前主流版本)
v3.x里创建动作有两种常用方式,推荐用更灵活的tween:
方式1:直接实例化RotateBy类
不再用.create(),直接new出实例即可:
openGates(){ const gateLeft = this.node.getChildByName("gateLeft"); const gateRight = this.node.getChildByName("gateRight"); // 修正节点名 const rotateLeft = new cc.RotateBy(2, 40); const rotateRight = new cc.RotateBy(2, -40); gateLeft.runAction(rotateLeft); gateRight.runAction(rotateRight); }
方式2:更推荐的cc.tween写法(v3.x官方主推)
tween功能更强大,支持链式调用、组合动作等,写法也更直观:
openGates(){ const gateLeft = this.node.getChildByName("gateLeft"); const gateRight = this.node.getChildByName("gateRight"); // 左门2秒内旋转40度 cc.tween(gateLeft) .to(2, { angle: gateLeft.angle + 40 }) .start(); // 右门2秒内旋转-40度 cc.tween(gateRight) .to(2, { angle: gateRight.angle - 40 }) .start(); }
如果你用的是Cocos Creator v2.x
v2.x里cc.RotateBy.create()是有效的,那你只需要先修正节点名的错误,再检查是否节点确实存在(名字大小写要完全匹配):
openGates(){ const gateLeft = this.node.getChildByName("gateLeft"); const gateRight = this.node.getChildByName("gateRight"); // 修正节点名 const rotateLeft = cc.RotateBy.create(2, 40); const rotateRight = cc.RotateBy.create(2, -40); gateLeft.runAction(rotateLeft); gateRight.runAction(rotateRight); }
如果还是报错,那大概率是你脚本没有正确挂载,或者节点名字写错导致获取到null,可以加个判断:
if (!gateLeft || !gateRight) { console.error("找不到门节点,请检查节点名称!"); return; }
最后提醒一下:Cocos Creator的API版本差异很大,写代码前最好对应自己的版本看官方文档,避免走弯路~
内容的提问来源于stack exchange,提问作者Siu Chung Chan
相关产品推荐
相关产品推荐

