2015년 6월 26일 금요일

corona sdk 에서 tiled 사용하기 10 – More Work on Platformer Characters


https://github.com/anthonymoralez/lime-tutorials/tree/master/tutorial-10



NOTE: This tutorial is copied from the original at OutlawGameTools.com

10 – More Work on Platformer Characters (플랫폼 캐릭터 좀 더 작업)

Difficulty: Beginner
Duration: 30 minutes
Description:
This tutorial is an extension to the previous tutorial so if you haven’t done that one yet please do so now. In this tutorial we will see how easy it is to give our player some basic movement controls. This is not the only way this can be achieved, this is just the way I am showing here, if you have a better way please email me.

Step 1: Creating your map

We will be using a slightly modified (well, simplified) version of the map we created in the last tutorial, it still has the player spawn point that we used before however the terrain is nice and flat with friction added.
이건 맨번 하던거 입니다.
The Map
You can download the map here.

Step 2: Creating the HUD (HUD를 만들기)

For the controls I have borrowed some simple images, they are not great but get the job done as far as this tutorial is concerned.
You can download all the images for the controls here.
Following are four blocks of code, all standard stuff that set up our controls as ui buttons. Please remember to include ui.lua in the normal way.
조정을 하기 위한 컨트롤 이미지를 다운받고 아래 코드를 넣습니다. local ui = require("lime.ui") 이런식으로 꼭 추가해주어야합니다.
local buttonLeft = ui.newButton{
    default = "buttonLeft.png",
    over = "buttonLeft_over.png",
    onEvent = onButtonLeftEvent
}
buttonLeft.x = buttonLeft.width / 2 + 10
buttonLeft.y = display.contentHeight - buttonLeft.height / 2 - 10
local buttonRight = ui.newButton{
    default = "buttonRight.png",
    over = "buttonRight_over.png",
    onEvent = onButtonRightEvent
}
buttonRight.x = buttonLeft.x + buttonRight.width
buttonRight.y = buttonLeft.y
local buttonA = ui.newButton{
    default = "buttonA.png",
    over = "buttonA_over.png",
    onEvent = onButtonAPress
}
buttonA.x = display.contentWidth - buttonA.width / 2 - 10
buttonA.y = display.contentHeight - buttonA.height / 2 - 10
local buttonB = ui.newButton{
    default = "buttonB.png",
    over = "buttonB_over.png",
    onEvent = onButtonBPress
}
buttonB.x = buttonA.x - buttonB.width
buttonB.y = buttonA.y
Your lovely new buttons should look something like this when the game is running.
여기까지 하면 화면에 아래와 같이 나오게 됩니다. 그리고 핸들러 함수가 빠졌는데 그건 다음 스텝에 있습니다. 충돌 관련 코드는 이전에 사용했던 코드를 넣어줍니다.

Controls

Step 3: Hooking up the controls (컨틀롤 후킹 하기)

Currently our controls are hooked up to nothing as we have not created any event handlers, to do so place the following code blocks somewhere above the button creation code from the previous step.
핸들러 함수들을 위쪽 함수들 보다 앞쪽에 넣습니다.
local onButtonLeftEvent = function(event)
end
local onButtonRightEvent = function(event)
end
local onButtonAPress = function(event)
end
local onButtonBPress = function(event)
end

Step 4: States and Directions (상태와 방향)

To keep track of what our player is doing we need a couple of variables that will be added to our player object, we also need some possible values for them and to make things easy to read we will define them at the top of our code.
상태와 방향 정보를 미리 변수값으로 만들어 둡니다.
local STATE_IDLE = "Idle"
local STATE_WALKING = "Walking"
local DIRECTION_LEFT = -1
local DIRECTION_RIGHT = 1
The values for the two state variables could be anything including numbers however in the next tutorial we will use them to play state animations so we want them as strings and we will use the direction values to simplify movement.

Step 6: Handling the events (이벤트 핸들링)

Now that our controls are hooked up and we have our state and direction variables set up it is time to actually do something with them, to do so please update the left and right button event handlers to look like the following:
local onButtonLeftEvent = function(event)
    if event.phase == "press" then
        player.direction = DIRECTION_LEFT
        player.state = STATE_WALKING
    else
        player.state = STATE_IDLE
    end
end
local onButtonRightEvent = function(event)
    if event.phase == "press" then
        player.direction = DIRECTION_RIGHT
        player.state = STATE_WALKING
    else
        player.state = STATE_IDLE
    end
end
All these functions do are set the player state to Walking and the player direction when the button has been pressed and then set the state back to Idle when the button has been released.
You then need to update the A button event handler to use the code from the previous tutorial for jumping.
이전에 사용한 점프 코드를 넣습니다. 하지만 A버튼을 눌렀을때로 변경해서 넣습니다.
local onButtonAPress = function(event)
    if player.canJump then
        player:applyLinearImpulse(0, -5, player.x, player.y)
    end
end

Step 7: The update function (업데이트 함수)

The update function is where all the “work” gets done, in actual fact it is very simple as we are only going to have simple movement.
업데이트 함수는 enterFrame 즉 한프레임이 지날때 마다 들어오게 됩니다.
local onUpdate = function(event)
    if player.state == STATE_WALKING then
        player:applyForce(player.direction * 10, 0, player.x, player.y)
    elseif player.state == STATE_IDLE then
        local vx, vy = player:getLinearVelocity()
        if vx ~= 0 then
            player:setLinearVelocity(vx * 0.9, vy)
        end
    end
end
Runtime:addEventListener("enterFrame", onUpdate)
The first part of this code checks whether your player is in the Walking state or the Idle state. If your player is in the Walking state then you need to apply a force based on the players direction and if your player is in the Idle state then it simply lowers the linear velocity until the player has stopped.

Step 8: Old code (예전 코드)

You also need to make sure you have the collision code from the previous tutorial in place to allow your player to jump.
점프가능 관련 충돌 코드를 그대로 재사용 합니다.
local function onCollision(self, event )
    if ( event.phase == "began" ) then
        if event.other.IsGround then
            player.canJump = true
        end
    elseif ( event.phase == "ended" ) then
        if event.other.IsGround then
            player.canJump = false
        end
    end
end
player.collision = onCollision
player:addEventListener( "collision", player )
As well as the player spawn code, making sure to place it directly after you call lime.loadMap().
Player layer에 적절한 위치를 잡아주는 PlayerSpawn 관련 함수들도 재사용합니다.
local onPlayerSpawnObject = function(object)
    local layer = map:getTileLayer("Player")
    player = display.newImage(layer.group, "guy.png")
    player.x = object.x
    player.y = object.y
end
map:addObjectListener("PlayerSpawn", onPlayerSpawnObject)

Step 9: Run your game

If you run your game now your player be able to walk left and right as well as jump when you press the appropriate buttons.
Resources:
Completed Project: git clone https://github.com/anthonymoralez/lime-tutorials

꼭 알아두세요.
1. lime은 프로젝트 최상위 폴더에 lime폴더 통째로 복사해서 넣습니다.
2. Layer는 높은쪽이 위쪽 레이어입니다.
3. Tiled에서 tileset의 프로퍼티는 이름과 값으로 구성됩니다.
4. 화면에 보이게한뒤 물리 설정을 해야합니다. local visual = lime.createVisual(map) => local physical = lime.buildPhysical(map)
5. 타일셋에 물리 객체는 HasBody로 합니다.
6. 타일셋 import/export로 현재 저장된 프로퍼티를 다른 맵파일(tmx)과 쉽게 공유할 수 있습니다.
7. 타일을 간단하게 애니메이션 시키는 방법,IsAnimated, frameCount=?,frameTime 이 있지만 오류 발생합니다. 사용 하려면 코드 수정해야 합니다.
8. 타일 에니메이션 또다른 방법은 IsAnimated tile.sprite:setSequence("animation1") 이걸 이용하세요
9. PlayerSpawn 만들기 : object layer사용 tool을 이용하여 위치 설정 Type을 PlayerSpawn 프로퍼티 playerImage=? 추가 후 코드 추가 map:addObjectListener("PlayerSpawn", onObject)
10. 물리세계를 만들려면 object layer 에 객체를 추가한뒤 type Body로 하면됩니다. 프로퍼티 bodyType=static 추가
11. 물리세계 정보를 런타임에 디버깅 Map>>Map Properties : Physics:DrawMode=hybrid?debug?normal 선택함
12. 물리세계 원형으로 처리하려면 프로퍼티 radius=? 추가함

13. Jump동작을 넣으려면 Groud일때만 점프 되도록 코드 추가하고 map에 Ground처리 해야함 object layer에 넣으려면 Object Type Body, IsGround, BodyType=static 이 되도록 해주고, 타일에 넣어주려면 HasBody, IsGround, bodyType=static 이 되도록 해줍니다.
14. HUD 컨트롤러는 ui.newButton 버튼을 이용해서 만듭니다.

댓글 없음:

댓글 쓰기