console
var RobotFace = 0;
var originPoint = [0, 0];
var viewType = 'follow';
var $robot = $('#robot');
var $result = $('#result');
var $stage = $('#stage');
$('button').on('click', function() {
robotMove(parseInt($(this).attr('data-direction')));
})
$('input').on('click',function(){
if($(this).prop('checked')){
viewType = 'follow'
}else{
viewType = 'fixed'
}
})
$(document).on('keyup', function(e) {
switch (e.keyCode) {
case 37:
robotMove(-90);
break;
case 38:
robotMove(0);
break;
case 39:
robotMove(90);
break;
case 40:
robotMove(180);
break;
}
})
function robotMove(moveType) {
var directionType = ((moveType + RobotFace) / 90) % 4;
RobotFace = directionType * 90;
switch (directionType) {
case 0:
originPoint[1] = originPoint[1] - 1;
break;
case 1:
case - 3 : originPoint[0] = originPoint[0] + 1;
break;
case 2:
case - 2 : originPoint[1] = originPoint[1] + 1;
break;
case 3:
case - 1 : originPoint[0] = originPoint[0] - 1;
break;
}
display();
}
function display() {
$robot.css('transform', 'translate(' + (originPoint[0] * 100) + 'px,' + (originPoint[1] * 100) + 'px) rotate(' + RobotFace + 'deg)');
if(viewType == 'follow'){
$stage.css('transform', 'rotate(' + (0 - RobotFace) + 'deg) translate(' + ( 0 - originPoint[0] * 100) + 'px,' + ( 0 - originPoint[1] * 100) + 'px)');
}
$result.text(originPoint[0] + ',' + originPoint[1]);
if (originPoint[0] == 0 && originPoint[1] == 0) {
$robot.addClass('isBack');
} else {
$robot.removeClass('isBack');
}
}
<button data-direction='0'>
↑
</button>
<button data-direction='180'>
↓
</button>
<button data-direction='-90'>
←
</button>
<button data-direction='90'>
→
</button><input type="checkbox" name='viewType' checked=checked/>跟随视角<br />
键盘方向键可以直接控制
<div id="stage">
<div id="robot">
↑
</div>
<div id="origin">
</div>
</div>
<span id='result'>
</span>
* {
padding: 0;
margin: 0;
}
html,body{
overflow:hidden;
}
button {
width: 100px;
height: 25px;
}
#stage {
position: absolute;
top: 50px;
bottom: 0;
right: 0;
left: 0;
overflow: visible;
transition:all 0.5s;
z-index:-1;
}
#origin {
width: 98px;
height: 98px;
border: solid 1px blue;
display: flex;
justify-content: center;
align-items: center;
position: absolute;
left: 50%;
top: 50%;
margin: -50px;
}
#robot {
width: 98px;
height: 98px;
border: solid 1px #ccc;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.38s;
position: absolute;
left: 50%;
top: 50%;
margin: -50px;
}
#robot.isBack {
border-color: green;
background-color: rgba(0, 255, 0, 0.4)
}