【发布时间】:2021-04-11 00:45:44
【问题描述】:
我现在遇到了一个困扰我好几天的数学难题。
我正在构建一个 JavaScript 游戏并尝试创建边界坐标来管理精灵的路径和移动,但似乎滞后/抖动/延迟对相互协调移动的不同实体造成了严重破坏。
我相信我必须计算抖动/滞后/偏移并以某种方式将其应用于坐标范围检测和移动功能,但我还没有正确破解代码并缓解未对齐的精灵。
以下是 CodeSandbox 中问题的复制,以及显示该问题的大部分代码: https://codesandbox.io/s/movetime-boundries-issue-example-2prow?file=/src/App.js
var obj = { x: 10, speed: 250 };
var obj2 = { x: 100 };
var objHighestX = { max: 0 };
var direction = 0;
var canvas = document.getElementById("mainScene");
var ctx = canvas && canvas.getContext("2d");
ctx.imageSmoothingEnabled = false;
ctx.font = "15px Courier";
var render = function () {};
var update = function (modifier) {
// console.log("Updating");
ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
ctx.fillRect(obj2.x, 60, 15, 15);
if (obj.x > objHighestX.max) {
objHighestX.max = obj.x;
}
ctx.fillText(String("X" + obj.x), 25, 100);
ctx.fillText(String("Furthest" + objHighestX.max), 125, 100);
if (obj.x >= obj2.x - 15) {
direction = 1;
} else if (obj.x <= 0) {
direction = 0;
}
if (direction === 0) {
obj.x += obj.speed * modifier;
ctx.clearRect(obj.x - 7, 9, 17, 17);
ctx.fillRect(obj.x, 60, 15, 15);
}
if (direction === 1) {
obj.x -= obj.speed * modifier;
ctx.clearRect(obj.x, 9, 17, 17);
ctx.fillRect(obj.x, 60, 15, 15);
}
};
var lastUpdate = Date.now();
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - lastUpdate;
lastUpdate = now;
update(delta / 1000);
render();
requestAnimationFrame(main);
};
main();
如果有人对我的案子有任何建议或疑问,我非常渴望听到。
也许我必须使用变化率来为边界创建偏移量?
我已经尝试过:
if (obj.x >= obj2.x - (15 * 1 * modifier))
但是我还没有把这个弄下来。提前谢谢大家。
【问题讨论】:
标签: javascript math canvas html5-canvas game-development