//导入触摸监听类型:input,Input //注:input,Input已替代了systemEvent,SystemEvent
//导入物体坐标类型:Vec3
import { _decorator, Component, Node,
input,Input,EventMouse,Vec3 } from 'cc';
const { ccclass, property } = _decorator;
@ccclass(‘jue_se_KongZhi’)
export class jue_se_KongZhi extends Component {
private _startJump = false; //判断是否开始跳跃
private _jumpStep = 0; //步长(1步or2步)
private _curJumpTime = 0; //当前跳跃的时间
private _jumpTime = 0.1; //跳跃总时间(必须0.1秒跳完)
private _curJumpSpeed = 0; //当前跳跃的速度
private _curPos = new Vec3(); //当前位置
private _targetPos = new Vec3(); //目标位置
private _deltaPos= new Vec3() ; //移动差
private _isMoving = false; //限制鼠标频繁点击
start() {
//定义:触摸事件
input.on(Input.EventType.MOUSE_UP,this.onMouseUp, this);
}
//监听按下的是:左键or右键
onMouseUp(event:EventMouse){
if (event.getButton() === 0){
this.jumpByStep(1); //赋值变量:按左键(既跳一步为1)
} else if(event.getButton() === 2){
this.jumpByStep(2);
}
}
//定义跳跃的代码
jumpByStep(step:number){
if(this._isMoving){ //限制鼠标频繁点击
return;
}
this._startJump = true; //true为执行跳跃
this._jumpStep = step; //跳跃的步长
this._curJumpSpeed = this._jumpStep / this._jumpTime; //跳跃速度:步长除以总时间(既越跳越快)
this._curJumpTime = 0; //重置当前速度
this.node.getPosition(this._curPos); //获取角色的当前位置
//获取角色当前真正的位置 向量叠加:既一(x,y,z)=二(x,y,z)+三(x,y,z)
Vec3.add(this._targetPos, this._curPos, new Vec3(step,0,0));
}
onOnceJumpEnd(){//自定义函数:跳跃已结束
this._isMoving = false;
}
//判断是否执行跳跃
update (deltaTime:number) {
if(this._startJump){ //判断_startJump不为空(既为true时才执行)
this._curJumpTime += deltaTime; //1:先让当前时间+每帧时间
if (this._curJumpTime > this._jumpTime){ //2:如果当前时间大于总时间
this.node.setPosition(this._targetPos); //3:那当前角色的位置就是目标位置
this._startJump = false; //4:跳跃结束了,并恢复_startJump为false
this.onOnceJumpEnd();//监听跳跃已结束
}
} else {
this.node.getPosition(this._curPos); //否则(既没有操作),仍需获取角色的当前位置
this._deltaPos.x = this._curJumpSpeed * deltaTime; //移动差:速度乘以时间
//获取角色当前真正的位置
Vec3.add(this._curPos, this._curPos, this._deltaPos);
this.node.setPosition(this._curPos); //最后赋值角色当前真正的位置
}
}
}