squidGame/tgx-games-client/assets/module_arean/scripts/GameScene/GameItem/Bullet.ts

104 lines
3.1 KiB
TypeScript
Raw Normal View History

2025-02-07 10:49:34 +08:00
import { _decorator, Component, Vec3 } from 'cc';
import { RoleController } from './RoleController';
const { ccclass, property } = _decorator;
@ccclass("Bullet")
export class Bullet extends Component {
speed: number = 0;
target: RoleController = null;
timer: number = 0;
direction: Vec3 = new Vec3(0, 1, 0); // 子弹飞行的方向
destroyed: Boolean = false;
distance: number = 0;
bulletDestroy() {
this.node.getChildByName("Node").active = false;
this.destroyed = true;
setTimeout(() => {
this.node.removeFromParent();
}, 1000);
}
init(target: RoleController, timer: number) {
this.target = target;
this.timer = timer;
const dx = target.node.position.x - this.node.position.x;
const dy = target.node.position.y - this.node.position.y;
// 使用 atan2 计算角度(弧度)
const angleRad = Math.atan2(dy, dx);
// 将弧度转换为度数(如果你的游戏引擎使用度数)
const angleDeg = angleRad * (180 / Math.PI);
this.node.angle = angleDeg;
}
update(dt: number) {
this.timer -= dt;
if (this.target && !this.destroyed && this.timer > 0) {
this.distance = Vec3.distance(this.node.worldPosition, this.target.node.worldPosition);
if (this.speed == 0) this.speed = this.distance / this.timer;
Vec3.subtract(this.direction, this.target.node.worldPosition, this.node.worldPosition);
Vec3.normalize(this.direction, this.direction);
// 计算子弹到目标的方向向量
const dx = this.target.node.worldPosition.x - this.node.worldPosition.x;
const dy = this.target.node.worldPosition.y - this.node.worldPosition.y;
// 计算角度(弧度)
let angleRad = Math.atan2(dy, dx);
// 转换为度数(如果你的引擎使用度数)
let angleDeg = angleRad * (180 / Math.PI);
// 调整角度以匹配子弹的默认朝向(如果子弹默认朝上,我们需要调整角度使其面向目标)
// 假设默认朝向是Y轴正方向即向上我们需要将角度从水平方向X轴旋转到目标方向
// 由于atan2返回的是从X轴正方向逆时针到点的角度我们需要进行一些调整
// 这里的-90度是将Y轴正方向向上转换为X轴正方向向右的偏移
// 然后根据目标位置调整角度
angleDeg = angleDeg + 90; // 调整为从“向上”到目标的角度
// 如果需要可以在这里添加一些范围检查或标准化确保角度在0-360度之间
if (angleDeg < 0) angleDeg += 360;
// 设置子弹的旋转角度
this.node.angle = -angleDeg; // 注意:这里的负号可能是因为你希望角度方向与默认朝向相反,根据具体情况调整
// 更新子弹位置
let displacement = Vec3.multiplyScalar(new Vec3, this.direction, this.speed * dt);
// 如果这里的缩放是为了效果,保留它;否则,可以移除缩放部分
let newPosition = Vec3.add(new Vec3, this.node.position, displacement);
this.node.setPosition(newPosition);
if (this.distance < 10) {
this.bulletDestroy(); // 假设近距离时销毁子弹
}
} else if (this.timer < 0) {
this.bulletDestroy();
}
}
}