2017-05-24 42 views
0

这个简单的游戏让精灵移动到用户点击的位置。我明白了,精灵会移动到位置,但我需要在点击位置停下来。此代码使精灵只在精灵向右下角移动时在点击位置停止。我如何解决这个问题,让它始终停在点击位置?移动一个精灵来点击位置并在那里停止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; 
     } 
    } 
} 

回答

0

所以你的精灵有速度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)) {