我不确定如何说出我的问题,所以让我举一个例子:
function foo() {
window.addEventListener("keydown", function(event) {
bar(event.keycode);
}
foo.prototype.bar = function (keycode) {
//code
}
Run Code Online (Sandbox Code Playgroud)
我尝试过使用this.bar(),但这会导致使用windowas this.有没有办法做到这一点,还是我必须手动调用另一个初始化方法?
通常情况下,浏览器在某些情况下会修改setInterval使用的实际时间间隔,甚至超过最小钳位.例如,我有以下代码:
function start() {
window.setInterval(function() {
update();
}, 1);
}
lastTime = new Date;
numFrames = 0;
lastFrames = 0;
function update() {
numFrames++;
if (new Date - lastTime >= 1000) {
lastFrames = numFrames;
numFrames = 0;
lastTime = new Date;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,lastFrames将给出我们在大约过去的秒数上的帧数.在Chrome,Firefox和Safari中使用时,此代码不会在一毫秒内运行.当然,每个浏览器在setInterval调用之间都有一个任意的最短时间,所以这是可以预料的.但是,随着页面继续运行,即使选项卡仍处于焦点,帧速率也将继续降低.我发现修复此问题的唯一方法是让浏览器执行某些操作.沿着这些方向的东西似乎使浏览器setInterval尽可能快地运行:
function start() {
window.setInterval(function() {
update();
}, 1);
}
lastTime = new Date;
numFrames = 0;
lastFrames = 0;
function update() {
numFrames++;
if (new Date - …Run Code Online (Sandbox Code Playgroud) 在我的代码中:
Vector2 colCircle = new Vector2();
colCircle = new Vector2((R * Math.Sin(D)), -(R * Math.Cos(D)));
Run Code Online (Sandbox Code Playgroud)
而:
R = 22.627
D = 89.214
Run Code Online (Sandbox Code Playgroud)
在我的计算器上检查时,X值是正确的,但Y值应该是-0.310,但在程序中它是-7.134.
有什么想法吗?
有一些looooong和饥饿的算法这样做,但到目前为止我还没有想出或发现任何特别快的东西.
我正以每秒45帧的速度运行程序.这是一个游戏,所以及时的用户输入很重要.似乎keydown事件有时会......慢慢地执行?好像轮询间隔有时会变化3或4秒.我绝对相信实际的游戏不会滞后,而是输入.我计划转移到GetKeyState(),但我仍然想知道KeyDown事件的实际轮询频率.
编辑:想我会发布一个链接到我使用的解决办法在这里.
例如(在JavaScript中):
//Not that I would ever add a method to a base JavaScript prototype...
//(*wink nudge*)...
Array.prototype.lastIndex = function() {
return this.length - 1;
}
console.log(array[array.lastIndex()]);
Run Code Online (Sandbox Code Playgroud)
VS
console.log(array[array.length - 1]);
Run Code Online (Sandbox Code Playgroud)
从技术上讲,后一种方法使用少一个字符,但也使用幻数.当然,在这种情况下,可读性可能不会受到影响,但魔术数字很糟糕.使用哪种更好的做法?
如果我是正确的,我在使用 Stopwatch.GetTimeStamp 时绝对不会出现 stackoverflow 错误,尤其是在启动程序后。
这是我的代码:
if (currentTicks >= lastTicks + interval)
{
lastTicks = currentTicks;
return true;
}
Run Code Online (Sandbox Code Playgroud)
currentTicks 由 Stopwatch.GetTimeStamp() 放置。这段代码位于一个名为“infinitely”的方法中(我用它来控制 FPS)。有人有什么想法吗?
编辑:主表单代码:
Game game;
public Form1()
{
InitializeComponent();
game = new Game(Stopwatch.Frequency / 45);
MainLoop();
}
public void MainLoop()
{
if (game.DrawStuff(Stopwatch.GetTimestamp()))
{
Invalidate();
}
MainLoop();
}`
Run Code Online (Sandbox Code Playgroud)
然后,游戏类:
public long lastTicks { get; set; }
public double interval { get; set; }
public Game(double Interval)
{
interval = Interval;
}
public bool DrawStuff(long currentTicks)
{ …Run Code Online (Sandbox Code Playgroud)