如何重新出现在地图的另一边,Javascript

时间:2016-09-24 10:52:51

标签: javascript

我在Javascript中创建了一个Asteroids游戏,但我需要一些帮助。让我试着解释一下我的意思,当船在地图的右侧飞出时,我如何让他重新出现在地图的左侧?

1 个答案:

答案 0 :(得分:0)

以下演示说明如何使离开屏幕边缘的船重新出现在屏幕的另一侧。



const ship = document.querySelector('#ship');
const screenWidth = 300, screenHeight = 200;
let x = screenWidth / 2, y = screenHeight / 2;
let thrustersOn = false;
let rot = 0;

const moveAndDrawShip = () => {
  if (thrustersOn) { // move forward if thrusters on
    x += Math.cos(rot / 180 * Math.PI) * 5; // recalculate coordinates
    y += Math.sin(rot / 180 * Math.PI) * 5;
    if (x < 0           ) x += screenWidth;  // offscreen left
    if (x > screenWidth ) x -= screenWidth;  // offscreen right
    if (y < 0           ) y += screenHeight; // offscreen top
    if (y > screenHeight) y -= screenHeight; // offscreen bottom
  }
  // move the ship, both position and rotation
  ship.setAttribute("transform", "translate(" + x + "," + y + ") rotate(" + rot + ")");
};

window.addEventListener('keydown', evt => {
  switch (String.fromCharCode(evt.keyCode)) {
    case "J": rot -= 10; thrustersOn = false; break;
    case "K":            thrustersOn = true ; break;
    case "L": rot += 10; thrustersOn = false; break;
  }
});
window.addEventListener('keyup', evt => { thrustersOn = false; });

window.setInterval(moveAndDrawShip, 30);
&#13;
<div>Click the image first. Then press J, K, L to move/spin.</div><svg width="300" height="200">
  <g stroke="black" stroke-width="1" fill="none">
    <rect id="border" x="10" y="10" width="280" height="180"></rect>
    <polygon id="ship" transform="translate(150,100) rotate(45)" points="-5,5 -5,-5 10,0"></polygon>
  </g>
</svg>
&#13;
&#13;
&#13;