95 lines
2.8 KiB
TypeScript
95 lines
2.8 KiB
TypeScript
import { _decorator, CCBoolean, CCInteger, Component, Node } from 'cc';
|
|
import { oops } from 'db://oops-framework/core/Oops';
|
|
import { GameEvent } from '../common/config/GameEvent';
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass('move')
|
|
export class move extends Component {
|
|
@property({ type: CCInteger })
|
|
speed: number = 2;
|
|
|
|
@property({ type: CCInteger })
|
|
maxX: number = 640;
|
|
|
|
@property({ type: CCInteger })
|
|
minX: number = -640;
|
|
|
|
@property({ type: CCInteger })
|
|
sc: number = 1; // 1: 从左到右, -1: 从右到左
|
|
@property
|
|
isMove:boolean=false
|
|
protected onLoad(): void {
|
|
oops.message.on(GameEvent.MAP_MOVE_END_LEFT, this.onMapMoveEndLeft, this);
|
|
oops.message.on(GameEvent.MAP_MOVE_END_RIGHT, this.onMapMoveEndRight, this);
|
|
}
|
|
start() {
|
|
// 根据移动方向设置初始位置
|
|
}
|
|
onMapMoveEndLeft() {
|
|
if(this.sc==-1){
|
|
this.isMove=true
|
|
this.setInitialPosition()
|
|
}
|
|
}
|
|
onMapMoveEndRight() {
|
|
if(this.sc==1){
|
|
this.isMove=true
|
|
this.setInitialPosition()
|
|
}
|
|
}
|
|
/**
|
|
* 根据移动方向设置初始位置
|
|
*/
|
|
setInitialPosition() {
|
|
if (this.sc > 0) {
|
|
// 从左到右移动,起点为 minX
|
|
this.node.setPosition(this.minX, this.node.position.y);
|
|
} else if (this.sc < 0) {
|
|
// 从右到左移动,起点为 maxX
|
|
this.node.setPosition(this.maxX, this.node.position.y);
|
|
}
|
|
}
|
|
|
|
update(dt: number) {
|
|
// 更新位置
|
|
if(this.isMove){
|
|
const newX = this.node.position.x + dt * this.speed * this.sc;
|
|
this.node.setPosition(newX, this.node.position.y);
|
|
// 检查边界并重置位置
|
|
this.checkBoundaries();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 检查边界并重置位置
|
|
*/
|
|
checkBoundaries() {
|
|
if (this.sc > 0) {
|
|
// 从左到右移动,到达右边界后回到左边界
|
|
if (this.node.position.x >= this.maxX) {
|
|
this.node.setPosition(this.minX, this.node.position.y);
|
|
this.isMove=false
|
|
oops.message.dispatchEvent(GameEvent.MAP_MOVE_END_LEFT)
|
|
}
|
|
} else if (this.sc < 0) {
|
|
// 从右到左移动,到达左边界后回到右边界
|
|
if (this.node.position.x <= this.minX) {
|
|
this.node.setPosition(this.maxX, this.node.position.y);
|
|
this.isMove=false
|
|
oops.message.dispatchEvent(GameEvent.MAP_MOVE_END_RIGHT)
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 动态改变移动方向
|
|
* @param direction 1: 从左到右, -1: 从右到左
|
|
*/
|
|
changeDirection(direction: number) {
|
|
this.sc = direction;
|
|
this.setInitialPosition();
|
|
}
|
|
}
|
|
|
|
|