cocos creator 划动屏幕以移动摄像机

博客讲述了作者在使用Cocos Creator开发Web应用时遇到的触摸事件响应问题。原本的代码在浏览器中运行正常,但在构建发布后,触摸事件失去反应,原因是变量作用域问题。修复该问题后,作者发现滚动效果生硬,尝试使用Vector3.Lerp改进但未成功。最终,通过引入ScrollView组件解决了滚动平滑问题。

本来代码是这么写的,在浏览器中运行也是好的。

cc.Class({
    extends: cc.Component,

    properties: {
        _begin: cc.Integer,
    	_end: cc.Integer,
    	_origin: cc.Integer,
    	_camera: cc.Node,
    },

    onLoad () {
        // 找到摄像机
        this.camera = cc.find("Canvas/Main Camera");
        // 开始触摸
	    this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
	    // 触摸中
	    this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    },

    onTouchStart(event) {
		let touch = event.touch;
		begin = touch.getLocationX();
		origin = this.camera.x;
	},

	onTouchMove(event) {
		let touch = event.touch;
		end = touch.getLocationX();
		dist = parseInt(begin-end);
		this.camera.x = origin + dist;
	},

});

但是构建发布到web之后就失去了触摸反应,打开控制台发现是begin未定义,后面我把那些属性都加上了this,就没有报错了。我想这个原因就在于打包的时候,cocos懂的规则,web不懂才导致的错误。 

cc.Class({
    extends: cc.Component,

    properties: {
        _begin: cc.Integer,
    	_end: cc.Integer,
    	_origin: cc.Integer,
    	_camera: cc.Node,
    },

    onLoad () {
        // 找到摄像机
        this.camera = cc.find("Canvas/Main Camera");
        // 开始触摸
	    this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
	    // 触摸中
	    this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    },

    start () {

    },

    onTouchStart(event) {
		let touch = event.touch;
		this.begin = touch.getLocationX();
		this.origin = this.camera.x;
        // cc.log("begin: " + begin);
	},

	onTouchMove(event) {
		let touch = event.touch;
		this.end = touch.getLocationX();
		this.dist = parseInt(this.begin-this.end);
		this.camera.x = this.origin + this.dist;
        // cc.log("dist: " + dist);
	},

});

但是!这个效果很生硬,百度说一般用Vector3.Lerp来平滑一下。我捣鼓了半天没弄好,后面改用scrollview组件来装,问题解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值