javascript敌人朝着方向移动

时间:2018-03-18 14:45:50

标签: javascript move direction sin cos

你可以在这里测试一下:http://xanderh.djoamersfoort.nl/informatica/spel3.php (当你走进一个激光时警察来了) 我希望警察走向你(x,y),但这段代码不起作用:

function police_move_loop(){
var police_x = parseInt(document.getElementById("police1").style.left);
var police_y = parseInt(document.getElementById("police1").style.top);
var delta_x = x - police_x;
var delta_y = y - police_y;
var politie_dir = Math.atan2(delta_y, delta_x) * 180 / Math.PI;
politie_dir+=270;
document.getElementById("police").style.transform = "rotate("+politie_dir+"deg)";
var police_vec_x = Math.cos(police_dir * Math.PI / 180);
var police_vec_y = Math.sin(police_dir * Math.PI / 180);
document.getElementById("police1").style.left = police_x+police_vec_x+"px";
document.getElementById("police1").style.top  = police_y+police_vec_y+"px";
setTimeout("police_move_loop()",10);
}

1 个答案:

答案 0 :(得分:0)

它看起来与

有关
document.getElementById("police1").style.top  = police_y+police_vec_y+"px";

即使在警察与玩家相交之后,y坐标也会彻底改变并仍然继续调用

setTimeout("police_move_loop()",10);

您可能想添加一个if语句,用于检查警察中心何时与玩家中心匹配。一旦警察和玩家碰撞,那么police_move_loop()就应该停止被召唤。