1. 通过键盘ADWS 控制物体的八方向移动
export default class TestMove extends cc.Component
{
//274,410(边界)
isLeft:boolean;
isRight:boolean;
isForward:boolean;
isBehind:boolean;
moveSpeed:number=400;
start ()
{
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,this.keyDownEvent,this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP,this.keyUpEvent,this);
}
update(dt)
{
if (this.isLeft)
{
this.node.x-=this.moveSpeed*dt;
if(this.node.x<=-274)
{
this.node.x=-274;
}
}
if(this.isRight)
{
this.node.x+=this.moveSpeed*dt;
if(this.node.x>=274)
{
this.node.x=274;
}
}
if(this.isForward)
{
this.node.y+=this.moveSpeed*dt;
if (this.node.y>410)
{
this.node.y=410;
}
}
if(this.isBehind)
{
this.node.y-=this.moveSpeed*dt;
if(this.node.y<-410)
{
this.node.y=-410;
}
}
}
keyDownEvent(event)
{
switch(event.keyCode)
{
case cc.macro.KEY.a:
this.isLeft=true;
break;
case cc.macro.KEY.d:
this.isRight=true;
break;
case cc.macro.KEY.w:
this.isForward=true;
break;
case cc.macro.KEY.s:
this.isBehind=true;
break;
}
}
keyUpEvent(event)
{
switch(event.keyCode)
{
case cc.macro.KEY.a:
this.isLeft=false;
break;
case cc.macro.KEY.d:
this.isRight=false;
break;
case cc.macro.KEY.w:
this.isForward=false;
break;
case cc.macro.KEY.s:
this.isBehind=false;
break;
}
}
onDestroy()
{
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN,this.keyDownEvent,this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP,this.keyUpEvent,this);
}
}
再Start 方法里面注册监听键盘按下的事件,因为是2d的,所以四方向,只需更改对应的分坐标即可。
2.在cocosCreator中,鼠标左中右键的监听事件如下:
start ()
{
this.node.on(cc.Node.EventType.MOUSE_DOWN,this.mouseEvent,this);
}
mouseEvent(event)
{
if (event.getButton()==0)
{
//console.log("left mouse");
let pos=event.getLocation();
//this.targetNode.position= this.node.convertToNodeSpaceAR(pos);
this.targetPos=this.node.convertToNodeSpaceAR(pos);
}
if(event.getButton()==2)
{
//console.log("right mouse");
}
if(event.getButton()==1)
{
//console.log("Middle mouse");
}
}
3.移动端触摸事件
常用的api如下,之后会使用这些api 写一些常见的人物控制方式(下一篇文章):