问题
I'm experimenting with EaselJS for the first time, and I'm trying to make a normal square move. I created used a Ticker to animate a square from the left to the right of the screen. It seemed choppy, so I raised the FPS of that ticker (via Ticker.setFPS(60)
).
My next step is to add keyboard events to allow the square to move. I've done so successfully, but the same choppiness has come back. I've tried setting the FPS of the Ticker to a higher rate, which isn't fixing my problem at all. Here is my code:
var c = document.getElementById("c");
var stage = new createjs.Stage("c");
var square = new createjs.Shape();
function init() {
square.graphics.beginFill("#3A5FCD").drawRect(0, 0, 75, 75);
square.x = 50;
square.y = 50;
stage.addChild(square);
stage.update();
//Update stage will render next frame
createjs.Ticker.addEventListener("tick", stage);
createjs.Ticker.addEventListener("tick", move);
createjs.Ticker.setFPS(60);
this.document.onkeydown = move;
}
function move(event) {
switch(event.keyCode) {
case 37:
square.x -= 10;
break;
case 39:
square.x += 10;
break;
case 38:
square.y -= 10;
break;
case 40:
square.y += 10;
break;
}
}
So, to sum up my question, how would I increase the FPS without being attached to the Ticker, or better yet, how can I attach the keyboard events to the Ticker?
Thanks in advance.
回答1:
Since you are modifying the shape position directly in the onkeydown
handler, the "choppiness" might just be the normal keyboard event behavior - the characters per second rate is OS dependent I think, and usually something like 30 Hz on the fastest setting.
You should probably decouple input handling from the movement logic: In the keyboard event handlers, just register which key(s) is/are currently pressed, and manipulate the object in a periodic "tick" function accordingly. Something along these lines:
var stage;
var square;
var keys = {};
function init() {
stage = new createjs.Stage("c");
square = new createjs.Shape();
square.graphics.beginFill("#3A5FCD").drawRect(0, 0, 75, 75);
square.x = 50;
square.y = 50;
stage.addChild(square);
createjs.Ticker.addEventListener("tick", tick);
createjs.Ticker.setFPS(60);
this.document.onkeydown = keydown;
this.document.onkeyup = keyup;
}
function keydown(event) {
keys[event.keyCode] = true;
}
function keyup(event) {
delete keys[event.keyCode];
}
function tick() {
if (keys[37]) square.x -= 10;
if (keys[38]) square.y -= 10;
if (keys[39]) square.x += 10;
if (keys[40]) square.y += 10;
stage.update();
}
来源:https://stackoverflow.com/questions/23717091/easeljs-keyboard-ticker-problems