2017-05-24 21 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보다 작을 때마다 그 위치에서 정지하십시오. 아래 Math.srqt 전화를 피하기 위해 같은

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 문을 수정할 수 있습니다.

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