我正在寫一個簡單的遊戲,用戶可以在其中移動一個精靈。通過點擊舞臺,精靈會移向該位置。我面臨的問題是我想爲這個精靈設置一個速度。我不知道用戶要點擊的值。我無法想象精靈速度總是如此的方式。最大移動速度sprite PIXI.js
PIXI.js的事情是你可以設置精靈的x和y移動速度。我希望這些移動速度的結果總是相同的,例如5.因此,如果精靈向下移動,y-速度將是5.當精靈正在對角移動時,對角線速度應該是5.我目前使用這個腳本,但我提出的解決方案並不完全工作,因爲每次點擊時速度都不相同。
有沒有人有任何想法如何解決這個問題?
var Container = PIXI.Container,
autoDetectRenderer = PIXI.autoDetectRenderer,
loader = PIXI.loader,
resources = PIXI.loader.resources,
Sprite = PIXI.Sprite;
var stage = new PIXI.Container(),
renderer = PIXI.autoDetectRenderer(1000, 1000);
document.body.appendChild(renderer.view);
PIXI.loader
.add("rocket.png")
.load(setup);
var rocket, state;
function setup() {
//Create the `tileset` sprite from the texture
var texture = PIXI.utils.TextureCache["animal.png"];
//Create a rectangle object that defines the position and
//size of the sub-image you want to extract from the texture
var rectangle = new PIXI.Rectangle(192, 128, 32, 32);
//Tell the texture to use that rectangular section
texture.frame = rectangle;
//Create the sprite from the texture
rocket = new Sprite(texture);
rocket.anchor.x = 0.5;
rocket.anchor.y = 0.5;
rocket.x = 50;
rocket.y = 50;
rocket.vx = 0;
rocket.vy = 0;
//Add the rocket to the stage
stage.addChild(rocket);
document.addEventListener("click", function(){
x = event.clientX - rocket.x;
y = event.clientY - rocket.y;
rocket.vmax = 5;
var total = Math.abs(x) + Math.abs(y);
var tx = x/total;
var ty = y/total;
rocket.vx = tx*rocket.vmax;
rocket.vy = ty*rocket.vmax;
});
state = play;
gameLoop();
}
function gameLoop() {
//Loop this function at 60 frames per second
requestAnimationFrame(gameLoop);
state();
//Render the stage to see the animation
renderer.render(stage);
}
function play(){
rocket.x += rocket.vx;
rocket.y += rocket.vy;
}
@Jonasw如何解決這個問題?然後,無論我點擊什麼,精靈都會以5的速度水平移動。 –