Javascript变量不通过occanvas函数和for循环 [英] Javascript Variable not passing through ocanvas function and for loop

查看:54
本文介绍了Javascript变量不通过occanvas函数和for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个变量没有通过 ocanvas 函数传递的问题.看起来变量在函数内部发生了变化,但并没有在函数外部发生变化.这是我的代码:

I'm having an issue with a variable not being passed through an ocanvas function. it appears that the variable is changing inside the function but isn't making it outside the function. here is my code:

                sonicSpeed2 = 0;
                sonicState2 = 0;

                canvas.bind("keypress", function () {
                    var keys = canvas.keyboard.getKeysDown();
                    var x;

                    sonicSpeed2 = 4;

                    for (x = keys.length; x > 0; x--) {
                        if (keys[x-1] == 16 && keys.length > 1) {
                            sonicSpeed2 = 15;
                            sonicState2 = 2;
                        }
                        if (keys[x-1] == 65) {
                            sonicState2 = 1;
                            sonicDirection2a = false;
                        }
                        if (keys[x-1] == 68) {
                            sonicState2 = 1;
                            sonicDirection2a = true;
                        }
                        if (keys[x-1] == 87) {
                            sonicState2 = 1;
                            sonicDirection2b = false;
                        }
                        if (keys[x-1] == 83) {
                            sonicState2 = 1;
                            sonicDirection2b = true;
                        }
                    }
                });

                if (sonicDirection2a == false) {
                    nullObject2.x -= sonicSpeed2;
                }
                else if (sonicDirection2a == true) {
                    nullObject2.x += sonicSpeed2;
                }

                if (sonicDirection2b == false) {
                    nullObject2.y -= sonicSpeed2;
                }
                else if (sonicDirection2b == true) {
                    nullObject2.y += sonicSpeed2;
                }

推荐答案

事件处理程序在未来的不确定时间执行.绑定事件处理程序,也就是你正在用 canvas.bind("keypress", ...) 做的事情,并没有执行该函数.之后 立即执行的内容.

The event handler is executed at an undetermined time in the future. Binding the event handler, which is what you are doing with canvas.bind("keypress", ...) does not executed the function. What comes after that is executed immediately.

如果你想对事件做一些响应,它必须在事件处理程序中或从事件处理程序中执行.

If you want to do something in response to the event it has to be in or executed from the event handler.

为什么我的变量在函数内部修改后没有改变?- 异步代码参考供参考.

这篇关于Javascript变量不通过occanvas函数和for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆