import { decorator, Animation, Component, EventMouse, Input, input, Node, Vec3 } from…
- User
import { _decorator, Animation, Component, EventMouse, Input, input, Node, Vec3 } from 'cc'; const { ccclass, property } = _decorator;
@ccclass('PlayerController') export class PlayerController extends Component { private _startJump=false; private _jumpTime=0.2; private _curJumpTime=0; private _jumpSpeed=0; private _targetPos=new Vec3(); private _curPos=new Vec3(); @property(Animation) public bodyAnim:Animation=null; start() { input.on(Input.EventType.MOUSE_DOWN,this.onMouseDown,this) }
update(deltaTime: number) { if(this._startJump){ this._curJumpTime+=deltaTime; if(this._curJumpTime>this._jumpTime){ this._startJump=false this.node.setPosition(this._targetPos) }else{ const curPos=this.node.position this.node.setPosition(curPos.x+this._jumpSpeed*deltaTime,curPos.y,curPos.z) } } } onMouseDown(event:EventMouse){ if(event.getButton()==0){ this.jumpByStep(1) }else if(event.getButton()==2){ this.jumpByStep(2) } } jumpByStep(step:number){ if(this._startJump) return const moveLength=step*40 this._startJump=true; this._curJumpTime=0; this._jumpSpeed=moveLength/this._jumpTime this._curPos=this.node.position this._targetPos=new Vec3(this._curPos.x+moveLength,this._curPos.y,this._curPos.z) this.bodyAnim.play("jump") } protected onDestroy(): void { input.off(Input.EventType.MOUSE_DOWN,this.onMouseDown,this) }}
为什么出现input.ts:342 Uncaught TypeError: Cannot read properties of null (reading 'play') at PlayerController.jumpByStep (PlayerController.ts:49:22) at PlayerController.onMouseDown (PlayerController.ts:33:17) at Eventified.emit (callbacks-invoker.ts:344:34) at InputEventDispatcher.dispatchEvent (input.ts:60:32) at Input._emitEvent (input.ts:337:33) at Input._dispatchOrPushEvent (input.ts:460:18) at input.ts:369:22 at Eventified.emit (callbacks-invoker.ts:346:25) at HTMLCanvasElement. (mouse-input.ts:171:31)这个问题?
- Assistant
这个错误提示你
bodyAnim是null,而不是对动画进行play操作的时候应该是一个有效的Animation实例。这个常见的问题通常是因为在 Cocos Creator 编辑器中没有正确地设置bodyAnim属性导致的。以下是一些可能的解决方案:
-
在 Cocos Creator 编辑器中正确分配组件:
- 确保你的节点上已经添加了动画组件 (Animation Component)。
- 在编辑器中选择添加了
PlayerController的节点,并在属性检查器中为bodyAnim分配正确的动画组件。你可以通过拖拽节点的 Animation 组件到bodyAnim属性来完成这种分配。
-
确认动画文件:
- 确保你拥有名为 "jump" 的动画并且它已经在 Animation 组件中设置。
-
脚本初始化:
- 确保这个属性在脚本初始化中没有被覆盖或错误地设置为
null。
- 确保这个属性在脚本初始化中没有被覆盖或错误地设置为
你可以通过修改初始化添加一个调试信息来进行检查,如:
start() { if (!this.bodyAnim) { console.error("Animation component is not assigned to bodyAnim!"); } input.on(Input.EventType.MOUSE_DOWN, this.onMouseDown, this); }运行游戏的时候,查看控制台是否输出了对应的错误信息,这样可以帮助确认
bodyAnim是否是null以及问题的来源。确保你按上述步骤正确设置了
bodyAnim后,问题应该能够得到解决。 -