2011-10-27 4 views
1

캔버스 요소로 작은 플랫폼 게임을 만들고 있는데 스프라이트를 사용하는 가장 좋은 방법을 모색하는 데 어려움을 겪고 있습니다.캔버스에서 스프라이트 프레임 애니메이션하기

캔버스는 애니메이션 GIF를 지원하지 않으므로 대신 할 수 없으므로 애니메이션 스프라이트로 필름 스트립을 만들어 캐릭터가 움직이는 것처럼 보일 것입니다. 이처럼 : 당신이 볼 수 있듯이

function player() { 

    this.idleSprite = new Image(); 
    this.idleSprite.src = "/game/images/idleSprite.png"; 
    this.idleSprite.frameWidth = 28; 
    this.idleSprite.frameHeight = 40; 
    this.idleSprite.frameCount = 12; 

    this.runningSprite = new Image(); 
    this.runningSprite.src = "/game/images/runningSprite.png"; 
    this.runningSprite.frameWidth = 34; 

    this.update = function() { 

    } 

    var frameCount = 1; 
    this.draw = function() { 
     c.drawImage(this.idleSprite, this.idleSprite.frameWidth * frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight); 
     if(frameCount < this.idleSprite.frameCount - 1) { frameCount++; } else { frameCount = 0; } 
    } 
} 

var player = new player(); 

, 내가 정의있어 유휴 스프라이트와 또한 프레임 너비와 프레임 수 : http://i.imgur.com/wDX5R.png

여기에 관련 코드입니다. 그런 다음 draw 메서드에서 그 속성을 사용하여 drawImage 메서드에 어떤 프레임을 그리는지 알려줍니다. 모든 것은 잘 작동하지만 draw 메소드 전에 정의 된 frameCount 변수에 만족하지 않습니다. 그것은 ... 해커하고 추한 것 같습니다. 사람들이 draw 방법 밖에 프레임을 추적하지 않고 같은 효과를 얻는 방법을 알고 있습니까? 또는 애니메이트 된 스프라이트를 캔버스에 그릴 때 더 좋은 대안이 될 수도 있습니다.

감사합니다.

+0

Slick2D (http://slick.cokeandcode.com/wiki/doku.php/http://slick.cokeandcode.com/)와 같은 2D 게임 라이브러리를 사용하여이 모든 것을 직접 구축해야 할 수 있습니다. 그것은 당신에게 많은 시간을 절약 할 것이며, 꼬임의 대부분은 이미 해결되었습니다. – jefflunt

+1

@normalcity 슬릭은 자바 스크립트가 아니라 자바 스크립트입니다. – helpermethod

답변

1

현재 시간의 일부에 따라 프레임을 선택할 수 있습니다 (예 :

this.draw = function() { 
    var fc = this.idleSprite.frameCount; 
    var currentFrame = 0 | (((new Date()).getTime()) * (fc/1000)) % fc; 
    c.drawImage(this.idleSprite, this.idleSprite.frameWidth * currentFrame, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight); 
} 

이렇게하면 애니메이션이 1 초 (1000은 밀리 초 값)가됩니다. 프레임 속도와 애니메이션에 따라 이것이 번쩍 거릴 수도 있지만 지속적인 카운터에 의존하지는 않습니다.

관련 문제