飞机大战(5)-碰撞及积分
参考敌机的生成
- 子弹由飞机生成,放在player_node节点
- 子弹重复使用,要使用预制体;
- 子弹新增了动画
①创建一个预制体 命名为playerBullet_prefab
② 双击预制体将bullet1图片拖入预制体
保存,关闭(场景编辑器里面的)
③ 发射子弹 player加入代码 @property(Prefab) playerBullet_prefab: Prefab; // 子弹预制体
将预制体和代码绑定
Player.ts加入创建子弹的代码
此时Player.ts的完整代码如下
import { _decorator, Component, EventTouch, Input, input, instantiate, Prefab, UITransform } from 'cc';
const { ccclass, property } = _decorator;@ccclass('Player')
export class Player extends Component {@property(Prefab) playerBullet_prefab: Prefab; // 子弹预制体private isPress; //是否按下start() {this.isPress = false;this.fireBullet();}onLoad() {input.on(Input.EventType.TOUCH_START, this.onTouchStart, this); //注册按下事件input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this); // 注册移动事件input.on(Input.EventType.TOUCH_END, this.onToucheEnd, this); // 注册离开事件}onToucheEnd(event: EventTouch) {this.isPress = false;}onTouchMove(event: EventTouch) {if (!this.isPress) {return;}const player = this.node.getChildByName("Player"); // 获取指定的组件if (player === null) {return;}const uiPos = event.getUILocation(); //获取世界坐标player.setWorldPosition(uiPos.x, uiPos.y, 0); // 设置指定坐标}onTouchStart(event: EventTouch) {const player = this.node.getChildByName("Player");if (player === null) {return;}const transform = player.getComponent(UITransform);const newRect = transform.getBoundingBoxToWorld(); //获取player组件框框if (newRect.contains(event.getUILocation())) {this.isPress = true;}}update(deltaTime: number) {}fireBullet() {this.schedule(() => {this.createOneBullet();}, 0.1);}// 创建一个敌机createOneBullet() {if (this.playerBullet_prefab == null) return; // 不然会报错 The thing you want to instantiate must be an objectconst player = this.node.getChildByName("Player");if (player === null) {return;}const bulletPrefab = instantiate(this.playerBullet_prefab); // 实例化一个对象 (动态生成)this.node.addChild(bulletPrefab); // 将对象 添加到某个 节点内const pos = player.getPosition();bulletPrefab.setPosition(pos.x, pos.y); // 设置子弹坐标}}
现在已经可以发射子弹了,但是子弹是是静止的,不会动,向下面这样
④ 让子弹动起来
创建脚本PlayerBullet.ts脚本里写的是子弹运动的逻辑
PlayerBullet.ts内容
import { _decorator, Component, Node, Vec3 } from 'cc';
const { ccclass, property } = _decorator;@ccclass('PlayerBullet')
export class PlayerBullet extends Component {private speed: number = 8;private _curPos: Vec3 = new Vec3();private _targetPos: Vec3 = new Vec3();private isExplo = false;start() {}update(deltaTime: number) {console.log('Bullet destroy');this.move(0, this.speed);// 移动到屏幕外之后进行销毁:const pos = this.node.getPosition(); // 获取角色当前位置let yy = pos.y;if (yy > 400) {this.node.destroy();//console.log('Bullet destroy');}}move(x, y) {this.node.getPosition(this._curPos); // 获取角色当前位置Vec3.add(this._targetPos, this._curPos, new Vec3(x, y, 0)); // 计算出目标位置this.node.setPosition(this._targetPos); // 将位移设置给角色}
}
接下来将脚本和预制体绑定起来,保存
现在子弹就能动了;
⑤ 让子弹旋转起来
新建一个动画体,命名为playerBullet_animation.amim 保存在assets/animation/文件夹中
动画属性添加spriteFrame
创建动画帧 每5帧插入一张新动画 (这里重复用了第一张)
播放方式改为循环播放,加载后播放
添加动画并绑定
保存,启动.
子弹就转起来了