Skip to content

Instantly share code, notes, and snippets.

@butchi
Created November 16, 2022 06:16
Show Gist options
  • Save butchi/bd8325f1ec6b012be448931049eba16b to your computer and use it in GitHub Desktop.
Save butchi/bd8325f1ec6b012be448931049eba16b to your computer and use it in GitHub Desktop.
自分と同じスピードで追従してくるやつ(ローグライクゲームより着想)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.stage {
display: block;
position: absolute;
left: 0;
top: 0;
width: 960px;
height: 540px;
border: 1px solid black;
overflow: hidden;
}
</style>
</head>
<body>
<div data-stage class="stage">
<canvas></canvas>
</div>
<script src="script.js"></script>
</body>
</html>
const stageElm = document.querySelector("[data-stage]")
const canvasElm = stageElm.querySelector("canvas")
const ctx = canvasElm.getContext("2d")
const cur = {
x: null,
y: null,
}
let acc = 0
enemyArr = []
curEnemyIndex = 0
const stageW = stageElm.clientWidth
const stageH = stageElm.clientHeight
canvasElm.width = stageW
canvasElm.height = stageH
stageElm.addEventListener("mousemove", evt => {
const x = evt.offsetX
const y = evt.offsetY
if (cur.x == null && cur.y == null) {
cur.x = x
cur.y = y
}
const diff = Math.sqrt((x - cur.x) ** 2 + (y - cur.y) ** 2)
acc += diff
ctx.clearRect(0, 0, stageW, stageH)
enemyArr.filter(enemy => enemy.isActive).forEach(enemy => {
if (diff > 15) {
return
}
const abs = Math.sqrt((x - enemy.x) ** 2 + (y - enemy.y) ** 2)
const arg = Math.atan2(y - enemy.y, x - enemy.x)
if (abs <= 15) {
enemy.isActive = false
return
}
enemy.x += Math.cos(arg) * diff
enemy.y += Math.sin(arg) * diff
ctx.fillStyle = "red"
ctx.beginPath()
ctx.arc(enemy.x, enemy.y, 3, 0, Math.PI * 2)
ctx.fill()
})
const encountRatio = 0.01
const newEnemyLen = Math.floor(acc * encountRatio - enemyArr.length)
for (let i = 0; i < newEnemyLen; i++) {
const x = Math.random() * stageW
const y = Math.random() * stageH
enemyArr.push({
isActive: true,
x,
y,
})
}
cur.x = x
cur.y = y
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment