类似《返校》和《无尽梦魇》的那种。
基本算法:
主要是解决精灵匀速直线运动的问题。
效果:
代码:
<div class="stage">
<div class="sence">
<div class="sprite"></div>
</div>
</div>
<style>
.stage{width: 100%; overflow: hidden; position: relative; }
.sence{width: 1024px; height: 350px; background:url(../assets/images/background.jpg)}
.sprite{width: 20px;height: 50px; background: #f4f74a; position: absolute;}
</style>
<script>
var sprite = document.querySelector(".sprite");
var from = {x:20, y:280};
var to = {x:200, y:270};
var timer;
sprite.style.left = from.x+'px';
sprite.style.top = from.y+'px';
function move(selector, from, to){
//偏移量,两条直角边长
var offset = {x:0,y:0};
offset.x = to.x - from.x;
offset.y = to.y - from.y;
//实际距离
var distance = Math.pow(offset.x,2) + Math.pow(offset.y,2);
distance = Math.sqrt(distance);
console.log(distance);
//速度 p/s 速度比等于直角三角形边长比
var v = 1; //斜边速度
var vX = (offset.x * v)/distance; //x轴上速度
var vY = (offset.y * v)/distance; //Y轴上速度
timer = setInterval(function(){
var left = parseFloat(selector.style.left) + vX;
var top = parseFloat(selector.style.top) + vY;
//判断是否移动结束
if(Math.round(left) == to.x && Math.round(top) == to.y){
from.x = to.x;
from.y = to.y;
to = {x:0,y:0};
clearInterval(timer);
}
selector.style.left = left.toString() + "px";
selector.style.top = top.toString() + "px";
},5);
};
function getClientCoordinate(event){
clearInterval(timer);
var from = {};
from.x = parseFloat(sprite.style.left);
from.y = parseFloat(sprite.style.top);
var to = {};
to.x = event.touches[0].clientX;
to.y = event.touches[0].clientY;
console.log("touch: ", from, to);
move(sprite, from, to);
}
document.addEventListener("touchstart", getClientCoordinate);
</script>
修改时间 2018-04-27
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。