- 碰撞
飞机与飞机碰撞
子弹与飞机碰撞
① 设置碰撞矩阵
设置碰撞矩阵,就是设置谁跟谁碰撞(添加Enemy,PlayerBullet,Player)
②设置刚体和碰撞体
两个预制体设置(Enemy和PlayerBullet)
注意点: 1. 都在预制体节点上,不在图片上; 2.碰撞体Collider2D中的Editing悬着好之后可以调整碰撞框
player_node节点刚体和碰撞体设置
上面是设置刚体和碰撞体的思路;
但是直到现在为止,没有调出跳出我想要的效果,那肯定是我哪里错了;
其实是敌机这块错了; 碰撞肯定是组件跟组件的碰撞,如果把脚本Enemy.ts和enemy_node绑定,碰撞的时候需要操控enemy_node子节点,所以不如把Enemy.ts和enemy_prefab预制体绑定在一块;同时设置刚体和碰撞体;
主要就是这些
同时修改Enemy.ts脚本
import { _decorator, Component } from 'cc';
const { ccclass, property } = _decorator;@ccclass('Enemy')
export class Enemy extends Component {start() {}update(deltaTime: number) {const pos = this.node.getPosition();if (pos.y < -400) {this.node.destroy();}else{this.node.setPosition(pos.x, pos.y - 5);}}
}
运行效果是一样的
注意每个刚体上 都选择监听
然后是碰撞函数: 参考: https://docs.cocos.com/creator/3.8/manual/zh/physics-2d/physics-2d-contact-callback.html
Enemy.ts
import { _decorator, Collider2D, Component, Contact2DType, IPhysics2DContact } from 'cc';
const { ccclass, property } = _decorator;@ccclass('Enemy')
export class Enemy extends Component {private isExplo = false;private collider:Collider2D;start() {this.collider = this.getComponent(Collider2D);if (this.collider) {this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this); // 碰撞函数注册}}onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {if (this.isExplo === false) { // 碰撞一次就行了this.isExplo = true;this.collider.destroy();this.scheduleOnce(() => { // 匿名函数 局部函数 this.node.destroy();}, 0.02);}}update(deltaTime: number) {const pos = this.node.getPosition();if (pos.y < -400) {this.node.destroy();} else {this.node.setPosition(pos.x, pos.y - 5);}}
}
PlayerBullet.ts代码,
import { _decorator, Collider2D, Component, Contact2DType, IPhysics2DContact, 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() {let collider = this.getComponent(Collider2D);if (collider) {collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);}}onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {// 只在两个碰撞体开始接触时被调用一次 if (this.isExplo === false) {this.isExplo = true;// 销毁子弹this.scheduleOnce(() => { // 匿名函数 局部函数 this.node.destroy();}, 0.1);}}update(deltaTime: number) {this.move(0, this.speed);// 移动到屏幕外之后进行销毁:const pos = this.node.getPosition(); // 获取角色当前位置let yy = pos.y;if (yy > 400) {this.node.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); // 将位移设置给角色}
}
现在已经可以打飞机了,而且玩家的飞机是无敌的,玩家飞机的碰撞, 不往上贴了
先这样, 晚安!