Browse Source

解决贪吃蛇时序bug

master
jiannibang 6 years ago
parent
commit
1123232fd1
  1. 2
      h5/snake/core/control.js
  2. 3
      h5/snake/core/view.js
  3. 23
      h5/snake/snake.js

2
h5/snake/core/control.js

@ -167,7 +167,6 @@ export default class control {
// start // start
start() { start() {
if (this.GAMEOVER) return;
// 蛇的随机运动方向 // 蛇的随机运动方向
let { leader, zone } = this.model; let { leader, zone } = this.model;
// 控制方向的变量是 this.direction。this.nextDirection 表示下一个方向 // 控制方向的变量是 this.direction。this.nextDirection 表示下一个方向
@ -187,6 +186,7 @@ export default class control {
restart() { restart() {
this.destroy(); this.destroy();
this.init(this.config); this.init(this.config);
this.view.destroyed = false;
this.start(); this.start();
this.event.dispatch("restart"); this.event.dispatch("restart");
} }

3
h5/snake/core/view.js

@ -77,6 +77,7 @@ export default class view {
this.timer = timer; this.timer = timer;
} }
destroy() { destroy() {
this.destroyed = true;
this.snake.clean(); this.snake.clean();
} }
@ -410,11 +411,13 @@ export default class view {
} }
// 渲染 // 渲染
render() { render() {
if (this.destroyed) return;
if (this.interval) { if (this.interval) {
const tween = new TWEEN.Tween({ t: 0 }); const tween = new TWEEN.Tween({ t: 0 });
this.currentTween = tween; this.currentTween = tween;
tween.to({ t: 1 }, this.interval); tween.to({ t: 1 }, this.interval);
tween.onUpdate(({ t }) => { tween.onUpdate(({ t }) => {
if (this.destroyed) return;
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.renderFood(t); this.renderFood(t);
this.renderSnake(t); this.renderSnake(t);

23
h5/snake/snake.js

@ -78,7 +78,9 @@ export default class SnakeClass extends SnakeControl {
this.start(); this.start();
this.addControl(); this.addControl();
} }
dispose() {}
dispose() {
this.destroy();
}
addControl() { addControl() {
let controller = this.buttons; let controller = this.buttons;
let curDirection; let curDirection;
@ -93,25 +95,10 @@ export default class SnakeClass extends SnakeControl {
deg270 = Math.PI + deg90, deg270 = Math.PI + deg90,
deg315 = Math.PI * 2 - deg45; deg315 = Math.PI * 2 - deg45;
controller.addEventListener(
"touchstart",
({ targetTouches: [{ clientX, clientY }] }) => {
checkDirection(clientX - x, clientY - y);
}
controller.addEventListener("click", ({ clientX, clientY }) =>
checkDirection(clientX - x, clientY - y)
); );
controller.addEventListener(
"touchmove",
({ targetTouches: [{ clientX, clientY }] }) => {
checkDirection(clientX - x, clientY - y);
}
);
controller.addEventListener("touchend", () => {
curDirection = undefined;
controller.className = "buttons snake-direction";
});
let checkDirection = (x, y) => { let checkDirection = (x, y) => {
let radian = Math.asin(y / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))); let radian = Math.asin(y / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
// 1~2象限 // 1~2象限

Loading…
Cancel
Save