110 lines
2.7 KiB
TypeScript
110 lines
2.7 KiB
TypeScript
import {
|
|
_decorator,
|
|
Component,
|
|
Vec3,
|
|
RigidBody,
|
|
input,
|
|
Input,
|
|
EventTouch,
|
|
} from "cc";
|
|
import { TrajectoryPreview } from "./TrajectoryPreview";
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass("GameMrg")
|
|
export class GameMrg extends Component {
|
|
@property(RigidBody)
|
|
rigidBody: RigidBody = null!;
|
|
|
|
@property(TrajectoryPreview)
|
|
trajectory: TrajectoryPreview = null!;
|
|
|
|
@property
|
|
maxPower: number = 25;
|
|
|
|
private startPos: Vec3 = new Vec3();
|
|
private endPos: Vec3 = new Vec3();
|
|
private isDragging: boolean = false;
|
|
|
|
start() {
|
|
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.onTouchEnd, this);
|
|
input.on(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
|
|
}
|
|
|
|
onDestroy() {
|
|
input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
|
|
input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
|
|
input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
|
|
input.off(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
|
|
}
|
|
|
|
onTouchStart(e: EventTouch) {
|
|
this.startPos.set(e.getLocation().x, e.getLocation().y, 0);
|
|
this.isDragging = true;
|
|
}
|
|
|
|
onTouchMove(e: EventTouch) {
|
|
if (!this.isDragging) return;
|
|
this.endPos.set(e.getLocation().x, e.getLocation().y, 0);
|
|
const dragVec = new Vec3(
|
|
this.startPos.x - this.endPos.x,
|
|
this.startPos.y - this.endPos.y,
|
|
0
|
|
);
|
|
if (dragVec.length() < 10) {
|
|
this.trajectory.hideTrajectory();
|
|
return;
|
|
}
|
|
|
|
// 主方向(始终向前 + 抬升)
|
|
const forward = new Vec3(0, 0.5, 1).normalize();
|
|
|
|
// 力度
|
|
const power = Math.min(dragVec.y * 0.05 + 10, this.maxPower);
|
|
|
|
// 左右弧线
|
|
const sideForce = dragVec.x * 0.02;
|
|
|
|
// 显示轨迹
|
|
this.trajectory.showTrajectory(
|
|
// this.rigidBody.node.worldPosition,
|
|
this.startPos.clone(),
|
|
forward,
|
|
power,
|
|
sideForce
|
|
);
|
|
}
|
|
|
|
onTouchEnd(e: EventTouch) {
|
|
if (!this.isDragging) return;
|
|
this.isDragging = false;
|
|
this.trajectory.hideTrajectory();
|
|
|
|
this.endPos.set(e.getLocation().x, e.getLocation().y, 0);
|
|
|
|
const dragVec = new Vec3(
|
|
this.startPos.x - this.endPos.x,
|
|
this.startPos.y - this.endPos.y,
|
|
0
|
|
);
|
|
|
|
if (dragVec.length() < 10) return;
|
|
|
|
// 主方向
|
|
const forward = new Vec3(0, 0.5, 1).normalize();
|
|
|
|
// 力度
|
|
const power = Math.min(dragVec.y * 0.05 + 10, this.maxPower);
|
|
|
|
// 左右弧线
|
|
const sideForce = dragVec.x * 0.02;
|
|
|
|
// 发射冲量
|
|
const impulse = forward.multiplyScalar(power);
|
|
impulse.x += sideForce;
|
|
|
|
this.rigidBody.applyImpulse(impulse);
|
|
}
|
|
}
|