移动精灵单击位置并停在那里 PIXIJS



这个简单的游戏使精灵移动到用户单击的位置。我让它工作,精灵移动到该位置,但我需要让它停止在点击位置。此代码使角色仅在精灵向右下角移动时停止在单击位置。如何解决此问题以使其始终停止在点击位置?

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("animal.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(){
    rocket.clickx = event.clientX;
    rocket.clicky = event.clientY;
    var x = event.clientX - rocket.x;
    var y = event.clientY - rocket.y; 
    rocket.vmax = 5;
    var total = Math.sqrt(x * x + y * 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;
    if(rocket.x >= rocket.clickx){
        if(rocket.y >= rocket.clicky){
            rocket.x = rocket.clickx;
            rocket.y = rocket.clicky;
        }
    }
}

所以你的精灵的速度是 5。然后让我们看看精灵和停止位置之间的距离。每当它小于 5 时,让它停在该位置。

function play(){
    var dx = rocket.x - rocket.clickx;
    var dy = rocket.y - rocket.clicky;
    if (Math.sqrt(dx * dx + dy * dy) <= 5) {
        rocket.x = rocket.clickx;
        rocket.y = rocket.clicky;
    }
    else {
        rocket.x += rocket.vx;
        rocket.y += rocket.vy;
    }
}

您可以像下面这样修改 if 语句以避免Math.srqt调用。

    if ((dx * dx + dy * dy) <= (5 * 5)) {

相关内容

最新更新