2014-06-24 3 views
3

현재 스프라이트가 캔버스에서 움직이는 경우 캔버스의 측면을 치면 튀어 나오게됩니다. 스프라이트가 캔버스의 임의의 위치에서 다른 방향으로 바뀌게하는 방법이 있습니까?스프라이트 이미지의 무작위 이동 위치

여기 방향의 변화에 ​​대한 내 코드이며 이동 방법 :

Fish.prototype.changeDirection = function() { 
    speedXSign = this.speedX > 0 ? 1 : -1; 
    speedYSign = this.speedY > 0 ? 1 : -1; 
    this.speedX = speedXSign * (1 + Math.random() * 2); 
    this.speedY = speedYSign * (1 + Math.random() * 2); 
}; 

Fish.prototype.move = function() { 
    this.animIndex++; 
    if (this.animIndex == animFrames.length) this.animIndex = 0; 

    this.xPos += this.speedX; 
    if ((this.xPos + this.frameWidth * this.frameScale/2) >= canvas.width && this.speedX > 0 || 
     (this.xPos - this.frameWidth * this.frameScale/2) <= 0 && this.speedX <= 0) { 
     this.speedX = -this.speedX; 
    } 

    this.yPos += this.speedY; 
    if ((this.yPos + this.frameHeight * this.frameScale/2) >= canvas.height && this.speedY > 0 || 
     (this.yPos - this.frameHeight * this.frameScale/2) <= 0 && this.speedY <= 0) { 
     this.speedY = -this.speedY; 
    } 
}; 

답변

4

한 매우 간단한 옵션은 임의의 시간을 선택하고 시간의 양 후 물고기의 변화 방향을 가지고있다. 내 첫번째 생각은 setTimeout을 사용하는 것입니다. 나는 당신의 changeDirection 함수에서의 비교가 역행했다는 것을 알아 차렸고 그래서 나는 그것을 임의의 시간 후에 호출하도록 설정했다.

Fish.prototype.changeDirection = function() { 
    var me = this; 
    var speedXSign = this.speedX < 0 ? 1 : -1; 
    var speedYSign = this.speedY < 0 ? 1 : -1; 
    this.speedX = speedXSign * (1 + Math.random() * 2); 
    this.speedY = speedYSign * (1 + Math.random() * 2); 
    var time = 1000 + 2000*Math.random(); 
    setTimeout(function() {me.changeDirection()}, time); 
}; 

시간 변수를 조정하여 회전 빈도를 변경할 수 있습니다. 당신이 새로운 물고기를 추가 할 때 그런 다음 당신은 너무 init은 다음과 같이 수있는 changeDirection 루프를 초기화해야합니다 :

또한
function init() { 
    frameWidth = imgFish.width/frameCount ; 
    frameHeight = imgFish.height ; 

    document.getElementById("button").onclick = function() { 
     // create another fish using the Fish class 
     var anotherFish = new Fish(xPos, yPos, speedX, speedY, imgFish, frameWidth, frameHeight); 
     // put this new fish into the fishes[] array 
     fishes.push(anotherFish) ; 
     // make it start changing directions 
     anotherFish.changeDirection(); 
     // draw this new fish 
     anotherFish.drawFish(); 
    } 
    animate(); 
} 

그렇게 밖으로 fish.changeDirection(); 라인을 방향마다 프레임을 변경하지 않으려는 animate 기능.

보조 메모로 매번 독립적으로 또는 무작위로 x 방향과 y 방향을 변경하도록 고려할 수 있습니다. 이것은 더 자연스러워 보입니다.

var speedXSign = Math.random() < 0.5 ? 1 : -1; 
    var speedYSign = Math.random() < 0.5 ? 1 : -1; 

편집 : JSFiddle

+0

@Bernard 당신은 별도의 질문을해야 속도를 변경해야하는 경우, Zacru 아주 잘 현재의 질문에 대답했다과 upvote에를 얻고 내게 투표 +1을 받아 들여야한다 좋은 작업. – Loktar