首页

通过js获取点击的id的进行游戏控制键改造代码示例

标签:点击事件     发布时间:2022-09-25   

一、前言

之前俄罗斯方块web版本游戏通过键盘上下左右方向键盘控制,但是在手机玩时没有键盘,如下图,需游戏界面放置四个虚拟方向键按钮,这样该游戏可以满足手机和电脑都能兼容使用了。

通过js获取点击的id的进行游戏控制键改造代码示例

二、代码说明

1、如上图位置,防止一个div图层,找一个方向键的背景图片,给四个方向键位置编码id值(如:上-btnTop、右-btnRight、下-btnBottom、左 - btnLeft)

2、获取点击的id代码示例

///获取点击标签的值(id)@b@    $(document).click(function (e) {@b@        var v_id = e.target.id;@b@        console.log(v_id);@b@        //var v_id2 = $(this).attr("id");@b@        //console.log(v_id2);@b@        //console.log(v_id == v_id2);@b@    });

3、具体案例实现代码如下,根据点击事件判断方向键id,进行触发不同方法(完整的代码下载,点击开始游戏

document.onclick = function(e){  @b@			if( _this.config.is_game_over == true ){@b@				console.log('game over');@b@				return;@b@			}@b@			_this.backup();@b@			let keyId = e.target.id;@b@			if (keyId == 'btnLeft') { //left@b@				_this.block.x--;@b@			}@b@			if (keyId == 'btnTop') { //up@b@				_this.do_rotate();@b@			}@b@			if (keyId == 'btnRight') { //right@b@				_this.block.x++;@b@			}@b@			if (keyId == 'btnBottom') { //down@b@				_this.block.y++;@b@				if( _this.chk_bottom() || _this.chk_knock() ){@b@					_this.restore();@b@					_this.do_solidity();@b@					_this.chk_game_over();@b@					_this.chk_full_line();@b@					_this.layer_display();@b@					_this.next_setting();@b@					_this.next_display();@b@					_this.block_setting();@b@					_this.block_display();@b@					@b@					return;@b@				}@b@			}@b@			// show@b@			if( _this.chk_overflow() || _this.chk_knock() ){@b@				_this.restore();@b@			}else{@b@				_this.block_display();@b@			}@b@			@b@        }
  • ◆ 相关内容