- 添加玩家飞机
1.创建player_node节点
2.将资源中Player图片拖入player_node节点
3.将Player的Position属性值调整为(0,-300) Content Size属性调整为(100 100)
4.点击运行,飞机在屏幕上了
2 用手指拖着飞机跑流程
① 要监听手指按下
②判断手指是否在飞机上
③移动飞机
④监听手指离开
创建一个脚本Player.ts , 场景节点选player_node节点, 将Player.ts拖入右边属性检查器,保存;
Player.ts脚本
csharp
import { _decorator, Component, EventTouch, Input, input, UITransform} from 'cc';
const { ccclass, property } = _decorator;
@ccclass('Player')
export class Player extends Component {
private isPress; //是否按下
start() {
this.isPress = false;
}
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) {
}
}