1. 蛇蛇大作战主角控制方式,主角根据 鼠标按下经过的轨迹移动
要用到触摸事件中的touchMove事件。具体实现如下:
touchStartEvent(event)
{
let touches=event.getTouches();
let touchPos=touches[0].getLocation();
this.isMoving=true;
this.nextPos=this.node.convertToNodeSpaceAR(touchPos);
}
touchMoveEvent(event)
{
let touches=event.getTouches();
let touchPos=touches[0].getLocation();
this.nextPos=this.node.convertToNodeSpaceAR(touchPos);
}
touchEndEvent(event)
{
this.isMoving=false;
}
update(dt)
{
if(!this.isMoving)
return;
let oldPos=this.player.position;
let dir=this.nextPos.sub(oldPos).normalize();
let newPos =oldPos.add(dir.mul(this.moveSpeed*dt));
this.player.setPosition(newPos);
}
在实际运行过程中,当player移动到鼠标所在位置时,鼠标如果仍在原地,player 会出现颤抖,原因是update方法每帧执行,每帧都在setposition,没有结束moving状态导致。
2.人物朝鼠标点击位置移动
LoL中人物移动方式
实现如下: 使用touchStart 方式
touchStartEvent(event)
{
// let touches=event.getTouches();
// let touchPos=touches[0].getLocation();
let touchPos=event.getLocation();
let worldPos;
//视口坐标--->世界坐标(如果摄像机在0,0 位置,则不需要转换。否则需要转换坐标系)
worldPos= this.cameraMain.getCameraToWorldPoint(touchPos, worldPos);
//世界坐标--->节点坐标
let targetPos=this.node.convertToNodeSpaceAR(worldPos);
this.walkToTarget(targetPos);
}
walkToTarget(dst:cc.Vec2)
{
let nowPos=this.player.position;
let dir=dst.sub(nowPos);
let len=dir.mag();
if(len<=0)
{
return;
}
this.walkTime=len/this.moveSpeed;
this.timeVal=0;
this.vx=this.moveSpeed*(dir.x/len);
this.vy=this.moveSpeed*(dir.y/len);
this.isMoving=true;
}
update(dt)
{
if(!this.isMoving) return;
this.timeVal+=dt;
if(this.timeVal>this.walkTime)
{
dt-=(this.timeVal-this.walkTime);
}
let sx=this.vx*dt;
let sy=this.vy*dt;
this.player.x+=sx;
this.player.y+=sy;
if(this.timeVal>=this.walkTime)
{
this.isMoving=false;
}
}
注意视口坐标和世界坐标以及结点坐标的转换,当相机的位置 和远点位置相同的时候,则不需要转换视口坐标到世界坐标,如果不与原点重合,则需要转换坐标,才能正确转入到节点坐标。
3.飞机大战 的移动方式
手指点击到飞机上,飞机跟着手指的运动运动
实现如下:
touchMoveEvent(event)
{
let worldPos;
worldPos=this.cameraMain.getCameraToWorldPoint(event.getLocation(),worldPos);
let nodePos=this.node.convertToNodeSpaceAR(worldPos);
this.player.setPosition(nodePos);
}