관리 메뉴

도드넷

JAVASCRIPT#74 - 자바스크립트 중력 연출하기 본문

창고/JS KING 포니 [중단]

JAVASCRIPT#74 - 자바스크립트 중력 연출하기

도드! 2016. 7. 26. 22:57
반응형



You should stop focusing what you can't do, and start doing something you can, its won't be anything big or fancy but something got to be better than nothing, and that's the start.


JAVASCRIPT#74 - 중력 연출하기


가속도 붙이면서 어떤 오브젝트의 위치를 Y축 방향으로 계속 끌어당기면 그게 중력인데...


function physics(obj, collider)
{
    var delta = 30;
    obj.fallingSpeed = Math.min(100, Math.max(-100, obj.fallingSpeed + obj.gravity * delta / 100));
    var newY = moveY(obj) + obj.fallingSpeed * delta / 100;
    var newX = moveX(obj);

    var collx = newX + collider.x;
    var colly = newY + collider.y;
    var newW = collider.width;
    var newH = collider.height;

    var collisions = tilemapCollide(mytilemap, {x: collx, y: colly, width: newW, height: newH});
          
    var i = 0;
    while (i < collisions.length) {
        var collision = collisions[i];
        i++;
        var collisionBox = {
            x1: collision.x,
            y1: collision.y,
            x2: collision.x + collision.width,
            y2: collision.y + collision.height
        };

        var x = intersect(collx, newX + newW, collisionBox.x1,collisionBox.x2);
        var y = intersect(colly, newY + newH, collisionBox.y1,collisionBox.y2);

        // Wall System.
        var diffx = (x[0] == newX)? x[0]-x[1] : x[1]-x[0];
        var diffy = (y[0] == newY)? y[0]-y[1] : y[1]-y[0];

        if (Math.abs(diffx) > Math.abs(diffy)){
            // displace along the y axis
             if(y[0] == newY)
             {
                console.log("^ Entering");
             }
             else
             {
                console.log("v Entering");
             }
             newY -= diffy;
             obj.speed = 0;
             if(obj.status=="jump" && diffy > 0){
                 obj.status="stand";
                 gf.setAnimation(obj, idle);
             }
            
        } else {
            // displace along the x axis
           
             if(x[0] == newX)
             {
                console.log("< Entering");
             }
             else
             {
                console.log("> Entering");
             }
            newX -= diffx;
           
        }
    }
    moveX(obj, newX);
    moveY(obj, newY);
}


자바스크립트 중력구현은 어려울것같지만 그것도 아니였다.


obj.fallingSpeed = Math.min(100, Math.max(-100, obj.fallingSpeed + obj.gravity * delta / 100));
var newY = moveY(obj) + obj.fallingSpeed * delta / 100;


두줄로 끝이나는데 폴링스피드가 -100 ~ 100 으로 정해지고 그 값을 유닛의 위치에 계속 더해주면 된다.


여기서 delta 값은 실제로 더해지는 값을 줄이기위해 나눠지는 100 이라는 수를 조절하기 위한 용도로 사용되고 있는 값이다. 만약 delta를 증가시키면 속도 증가량은 크게 증가한다.


식에서 obj.gravity * delta / 100 은 중력가속도로 봐도 된다.


obj가 가지고 있는 fallingspeed 값은 초기 스피드이다.

obj가 가지고 있는 gravity 값은 fallingspeed를 증가시킬, 더해질 고유 속도값이다.







반응형
Comments