我正在编写一个简单的游戏,用户可以在精灵中移动。通过单击舞台,精灵移动到该位置。我面临的问题是我想为这个精灵设置一个速度。我不知道用户要点击的值。我无法想象精灵的速度总是一样的。
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;
}
答案 0 :(得分:2)
这个怎么样?这将使x和y标准化。
var total = Math.Sqrt(x * x + y * y);
它看起来x和y缺失' var'。
var x = event.clientX - rocket.x;
var y = event.clientY - rocket.y;