본문 바로가기

「zim.js」 물리엔진 적용(2)

by Recstasy 2021. 7. 25.

 

 

 

물리엔진(1)편에 이어 간단한 당구게임 기초를 제작해보자.

 

일단, 구현결과를 보면 공(circle)뒤쪽에 마우스를 클릭했을 때,

거리에 따라 공의 파워가 달라지며,

3쿠션으로 움직일 수 있다.

 

 

 

 

 

텍스처를 사용해서 원과 사각형을 '4구공'으로 변경한다면,

zim.js로 당구게임을 제작가능하다.

 

 

[기본코드]

//생략...
    const physics = new Physics(0);
    
    const ball2 = new Circle(20)
                .sca(.7)
                .centerReg(stage)
                .addPhysics({shape:'circle', restitution:.7})
    			
    stage.on('stagemousedown', e=>{
	   ball2.impulse(
		(ball2.x - e.stageX/stage.scaleX)*.15,
		(ball2.y - e.stageY/stage.scaleY)*.15
	   )
	});
 

 //생략...

 

기본코드에서 physics인스턴스를 생성하고,

stage에 circle(ball) 및 stage마우스 이벤트를 설정한다.

-물리엔진 적용(1)편-

 

이후, Rigid Body(충돌을 감지하며, 움직이지 않는 물리객체)를 담당할 사각형을 생성한다.

 

[코드]

//생략...

    const physics = new Physics(0);
    const emitter = new Emitter({obj:new Rectangle(10,10, red), startPaused:true})
    
    const ball2 = new Circle(20)
                .sca(.7)
                .centerReg(stage)
                .addPhysics({shape:'circle', restitution:.7})
    			
	stage.on('stagemousedown', e=>{
	   ball2.impulse(
		(ball2.x - e.stageX/stage.scaleX)*.15,
		(ball2.y - e.stageY/stage.scaleY)*.15
	   )
	});
    
    const target = new Rectangle(25, 25, red)
    		.centerReg()
    		.loc(rand(stageW), rand(stageH))
    		.addPhysics({
			dynamic:false
		})

//생략...

 

 

zim.js에서는 접촉을 감지할 수 있는 여러 방법이 있다.

hitTestCircle, hitTestxxx와 같은 메서드들이 대표적이며,

물리엔진에서는 contact( )메서드를 사용한다.

 

 

[code]

//생략...

    const physics = new Physics(0);
    const emitter = new Emitter({obj:new Rectangle(10,10, red), startPaused:true})
    
    const ball2 = new Circle(20)
                .sca(.7)
                .centerReg(stage)
                .addPhysics({shape:'circle', restitution:.7})
                .contact((obj)=>{
                	if(obj == target){
                    	   target.visible = false;
                      	   emitter.center(stage).loc(target).spurt(5);
                      
                      	   timeout(.5, ()=>{
                        	   target.visible = true;
                          	   target.body.x = rand(stageW);
                          	   target.body.y = rand(stageH);
                           })
                       }
                })
    			
	stage.on('stagemousedown', e=>{
	   ball2.impulse(
		(ball2.x - e.stageX/stage.scaleX)*.15,
		(ball2.y - e.stageY/stage.scaleY)*.15
	   )
	});
    
    const target = new Rectangle(25, 25, red)
    		.centerReg()
    		.loc(rand(stageW), rand(stageH))
    		.addPhysics({
			dynamic:false
		})

//생략...

 

.contact( )메서드는 접촉한 객체를 콜백으로 반환한다.

위에서는 공과 부딪친 객체(사각형)를 반환하여

숨기고(visible:false), 0.5초 후에 새로운 위치에서 보이도록 구현하고 있다.  

 

 

당구와 같은 게임을 구현하기 위해서는 좀더 세부적인 변수값이 반영되어야 하겠지만 원리는 동일하다.

당구 뿐 아니라 독특한 텍스처를 활용한 물리게임을 제작하기에 zim.js는 상당히 효율적이다.

간단한 물리엔진 앱을 구축하는데 굳이 유니티를 사용할 필요가 없다. 

 

 

댓글

최신글 전체

이미지
제목
글쓴이
등록일