cocos-creator学习笔记2(触摸屏幕,鼠标锁定控制节点移动)

触摸控制就是我们常在手机上用手按住屏幕上的某物体拖动的实现
1.首先:
在onLoad里面打开对触摸或者鼠标锁定的控制开关
这里的hero是我创建的节点,你们用什么节点就替换成相应的节点就可以
在这里插入图片描述
2.接下来开始编写onTouchMove函数了
在这里插入图片描述
event是接受控制的事情。
顺带学习一下getLocation()这个函数,查看API如下,返回一个二维坐标
在这里插入图片描述
在这里插入图片描述

getDelta() 函数的API如上,返回也是一个二维坐标。
接下来这两个貌似没什么大作用,但最好加上,这人可以让程序避免一下意外的错误
在这里插入图片描述

完整代码:(将hero换成你们要实现监控的节点就可以)


cc.Class({
    extends: cc.Component,

    properties: {
       //bj_1:cc.Node,
       //bj_2:cc.Node,
       hero:cc.Node,
       //bullet:cc.Prefab,
    },

    onLoad () 
    {
        //this.bullet_sx=0;
        this.hero.on(cc.Node.EventType.TOUCH_MOVE,this.onTouchMove,this) 
        //手指按下时开始监控
        this.hero.on(cc.Node.EventType.TOUCH_END,this.onTouchEnd,this);
        //手指松开时终止监控
        this.hero.on(cc.Node.EventType.TOUCH_CANCEL,this.onTouchCancel,this);
        //终止对该事件监控
    },
    onTouchMove(event){
       var oldPos = event.getLocation();
       //console.log(oldPos,this.role.x,this.role.y);
       var delta = event.getDelta();
       this.hero.x += delta.x;
       this.hero.y += delta.y;
    },
    onTouchEnd:function(){
        cc.log('触摸结束');
    },
    onTouchCancel:function(){
        cc.log('触摸取消')
    },
   /* MoveBj:function(){
        this.bj_1.y -= 8;
        this.bj_2.y -= 8;
        if(this.bj_1.y <= -this.bj_1.height)
            this.bj_1.y = this.bj_1.height;
        if(this.bj_2.y <= -this.bj_1.height)
            this.bj_2.y = this.bj_1.height;*/
    },
   /* CreateBullet:function(){
        var Bullet = cc.instantiate(this.bullet);
        this.node.addChild(Bullet);
        Bullet.setPosition(this.hero.x,this.hero.y + this.hero.height/2+10);
        //Bullet.getComponent('bullet').game = this;
    },*/
    update (dt)
    {
        /*this.bullet_sx++;
        if(this.bullet_sx >= 16)
        {
            this.CreateBullet();
            this.bullet_sx=0;
        }
        this.MoveBj();   //主游戏场景轮番移动的函数*/
    },
});

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌晨小街

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值