Created
November 30, 2016 09:41
-
-
Save hakatashi/4758a05502fec1da8ed2cf7a77e4862e to your computer and use it in GitHub Desktop.
TSG 第12回Web分科会 実習課題
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>SVG Shooting</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.4.1/snap.svg.js"></script> | |
<style> | |
body { | |
margin: 0; | |
} | |
svg { | |
display: block; | |
width: 100vmin; | |
height: 100vmin; | |
margin: 0 auto; | |
} | |
</style> | |
<script> | |
document.addEventListener('DOMContentLoaded', () => { | |
class Bullet { | |
constructor({x, y, angle}) { | |
this.x = x; | |
this.y = y; | |
this.angle = angle; | |
this.svg = null; // 何か書く | |
} | |
// 弾を動かす | |
step() { | |
this.x += Math.cos(this.angle); | |
this.y += Math.sin(this.angle); | |
// 何か書く | |
// 画面外に出た場合 | |
if (this.x < 0 || 100 < this.x || this.y < 0 || 100 < this.y) { | |
// 何か書く | |
bullets.delete(this); | |
} | |
} | |
} | |
const snap = Snap('#snap'); | |
const background = snap.rect(0, 0, 100, 100).attr({ | |
fill: 'black', | |
}); | |
let clock = 0; | |
const bullets = new Set(); | |
let selfX = 50; | |
let selfY = 80; | |
const self = null; // 何か書く | |
let dead = false; | |
const moves = { | |
37: {x: -1, y: 0}, | |
38: {x: 0, y: -1}, | |
39: {x: 1, y: 0}, | |
40: {x: 0, y: 1}, | |
}; | |
const pressedKeys = new Map(); | |
window.addEventListener('keydown', (event) => { | |
pressedKeys.set(event.which, true); | |
}); | |
window.addEventListener('keyup', (event) => { | |
pressedKeys.set(event.which, false); | |
}); | |
const distance = (xA, xB, yA, yB) => ( | |
Math.sqrt((xA - xB) * (xA - xB) + (yA - yB) * (yA - yB)) | |
); | |
setInterval(() => { | |
clock++; | |
// 弾を動かす | |
for (const bullet of bullets) { | |
bullet.step(); | |
} | |
// 弾を射出する | |
const newBullet = new Bullet({ | |
x: 50, | |
y: 50, | |
angle: (clock * 137 / 360) * Math.PI * 2, | |
}); | |
bullets.add(newBullet); | |
// 自機を移動する | |
[37, 38, 39, 40].forEach((keycode) => { | |
if (pressedKeys.get(keycode) && !dead) { | |
const move = moves[keycode]; | |
selfX += move.x * 1; | |
selfY += move.y * 1; | |
selfX = Math.max(0, Math.min(selfX, 100)); | |
selfY = Math.max(0, Math.min(selfY, 100)); | |
// 何か書く | |
} | |
}); | |
// 当たり判定 | |
for (const bullet of bullets) { | |
if (!dead && distance(bullet.x, selfX, bullet.y, selfY) < 3) { | |
// Game Over | |
// 何か書く | |
dead = true; | |
} | |
} | |
}, 1000 / 30); | |
}); | |
</script> | |
</head> | |
<body> | |
<svg id="snap" xmlns="http://www.w3.org/2000/svg" width="100vmin" height="100vmin" viewBox="0 0 100 100"> | |
</svg> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment